refactor: testing from the beginning. a journey in 150k lines of tests to none
This commit is contained in:
651 files changed
-146443
No files matched your search
@@ -1,94 +0,0 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// testApprover is a stub ApprovalRequester for tests.
|
||||
type testApprover struct {
|
||||
decision ApprovalDecision
|
||||
err error
|
||||
}
|
||||
|
||||
func (a *testApprover) RequestApproval(context.Context, string, string) (ApprovalDecision, error) {
|
||||
return a.decision, a.err
|
||||
}
|
||||
|
||||
func TestApprovalDecisionConstantsAreDistinct(t *testing.T) {
|
||||
seen := make(map[ApprovalDecision]bool)
|
||||
for _, d := range []ApprovalDecision{
|
||||
ApprovalApproved,
|
||||
ApprovalPermanentlyApproved,
|
||||
ApprovalDenied,
|
||||
} {
|
||||
if seen[d] {
|
||||
t.Errorf("duplicate decision value %d", d)
|
||||
}
|
||||
seen[d] = true
|
||||
}
|
||||
}
|
||||
|
||||
func TestApproverStubReturnsDecision(t *testing.T) {
|
||||
s := &testApprover{decision: ApprovalApproved}
|
||||
d, err := s.RequestApproval(context.Background(), "tool", "desc")
|
||||
if err != nil || d != ApprovalApproved {
|
||||
t.Errorf("(decision=%v, err=%v)", d, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApproverStubReturnsDenial(t *testing.T) {
|
||||
s := &testApprover{decision: ApprovalDenied}
|
||||
d, err := s.RequestApproval(context.Background(), "x", "")
|
||||
if err != nil || d != ApprovalDenied {
|
||||
t.Errorf("(decision=%v, err=%v)", d, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApproverStubReturnsError(t *testing.T) {
|
||||
s := &testApprover{err: errors.New("timeout")}
|
||||
_, err := s.RequestApproval(context.Background(), "x", "")
|
||||
if err == nil {
|
||||
t.Error("expected error from stub")
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrApprovalDeniedIsDistinguishable(t *testing.T) {
|
||||
if !errors.Is(ErrApprovalDenied, ErrApprovalDenied) {
|
||||
t.Error("ErrApprovalDenied does not match itself")
|
||||
}
|
||||
if errors.Is(ErrApprovalDenied, ErrApprovalNotConfigured) {
|
||||
t.Error("ErrApprovalDenied should not match ErrApprovalNotConfigured")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolApprovalTimeoutIsReasonable(t *testing.T) {
|
||||
if ToolApprovalTimeout < time.Minute {
|
||||
t.Errorf("timeout %v is too short for a human to decide", ToolApprovalTimeout)
|
||||
}
|
||||
if ToolApprovalTimeout > 5*time.Minute {
|
||||
t.Errorf("timeout %v is too long for an LLM connection to hold", ToolApprovalTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApprovalContextRoundTrip(t *testing.T) {
|
||||
a := &testApprover{decision: ApprovalApproved}
|
||||
ctx := WithApprovalRequester(context.Background(), a)
|
||||
|
||||
got := ApprovalFromContext(ctx)
|
||||
if got == nil {
|
||||
t.Fatal("ApprovalFromContext returned nil")
|
||||
}
|
||||
d, err := got.RequestApproval(context.Background(), "x", "")
|
||||
if err != nil || d != ApprovalApproved {
|
||||
t.Errorf("round-tripped approver: (decision=%v, err=%v)", d, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApprovalFromContextReturnsNilWhenNotStored(t *testing.T) {
|
||||
if got := ApprovalFromContext(context.Background()); got != nil {
|
||||
t.Error("ApprovalFromContext should return nil when nothing was stored")
|
||||
}
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestAvailabilityCacheAlwaysAvailable(t *testing.T) {
|
||||
c := NewAvailabilityCache(nil, 30*time.Second, 60*time.Second)
|
||||
|
||||
if !c.Check() {
|
||||
t.Error("nil CheckFn should mean always available")
|
||||
}
|
||||
if !c.CachedAvailable() {
|
||||
t.Error("nil CheckFn should mean always available")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAvailabilityCacheCheck(t *testing.T) {
|
||||
t.Run("positive result cached", func(t *testing.T) {
|
||||
calls := 0
|
||||
c := NewAvailabilityCache(func() bool {
|
||||
calls++
|
||||
return true
|
||||
}, 30*time.Second, 60*time.Second)
|
||||
|
||||
// First call -- evaluates.
|
||||
if !c.Check() {
|
||||
t.Error("expected true")
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Errorf("expected 1 call, got %d", calls)
|
||||
}
|
||||
|
||||
// Second call -- cached.
|
||||
if !c.Check() {
|
||||
t.Error("expected true (cached)")
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Errorf("expected still 1 call (cached), got %d", calls)
|
||||
}
|
||||
|
||||
// CachedAvailable reports the last result.
|
||||
if !c.CachedAvailable() {
|
||||
t.Error("CachedAvailable should be true")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("negative result cached with failure grace", func(t *testing.T) {
|
||||
calls := 0
|
||||
c := NewAvailabilityCache(func() bool {
|
||||
calls++
|
||||
return false
|
||||
}, 100*time.Millisecond, 300*time.Millisecond)
|
||||
|
||||
// First call.
|
||||
if c.Check() {
|
||||
t.Error("expected false")
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Errorf("expected 1 call, got %d", calls)
|
||||
}
|
||||
|
||||
// Still within failure grace period -- cached false.
|
||||
if c.Check() {
|
||||
t.Error("expected false (cached within grace)")
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Errorf("expected still 1 call, got %d", calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestAvailabilityCacheExpiry(t *testing.T) {
|
||||
calls := 0
|
||||
c := NewAvailabilityCache(func() bool {
|
||||
calls++
|
||||
return true
|
||||
}, 20*time.Millisecond, 50*time.Millisecond)
|
||||
|
||||
// First call.
|
||||
c.Check()
|
||||
if calls != 1 {
|
||||
t.Fatalf("expected 1 call, got %d", calls)
|
||||
}
|
||||
|
||||
// Wait for TTL to expire.
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
|
||||
// TTL expired -- re-evaluates.
|
||||
c.Check()
|
||||
if calls != 2 {
|
||||
t.Errorf("expected re-evaluation after TTL expiry, got %d calls", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAvailabilityCacheInvalidate(t *testing.T) {
|
||||
calls := 0
|
||||
c := NewAvailabilityCache(func() bool {
|
||||
calls++
|
||||
return true
|
||||
}, 3600*time.Second, 3600*time.Second)
|
||||
|
||||
// Fill cache.
|
||||
c.Check()
|
||||
if calls != 1 {
|
||||
t.Fatalf("expected 1 call, got %d", calls)
|
||||
}
|
||||
|
||||
// Cached call.
|
||||
c.Check()
|
||||
if calls != 1 {
|
||||
t.Error("expected cache hit")
|
||||
}
|
||||
|
||||
// Invalidate.
|
||||
c.Invalidate()
|
||||
|
||||
// Re-evaluates.
|
||||
c.Check()
|
||||
if calls != 2 {
|
||||
t.Errorf("expected re-evaluation after invalidation, got %d calls", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAvailabilityCacheLastChecked(t *testing.T) {
|
||||
c := NewAvailabilityCache(func() bool { return true }, 30*time.Second, 60*time.Second)
|
||||
|
||||
if !c.LastChecked().IsZero() {
|
||||
t.Error("LastChecked should be zero before first Check()")
|
||||
}
|
||||
|
||||
before := time.Now()
|
||||
c.Check()
|
||||
after := time.Now()
|
||||
|
||||
lc := c.LastChecked()
|
||||
if lc.Before(before) || lc.After(after) {
|
||||
t.Errorf("LastChecked = %v, expected between %v and %v", lc, before, after)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewAvailabilityCacheFromEntry(t *testing.T) {
|
||||
e := ToolEntry{
|
||||
Name: "test-tool",
|
||||
Handler: noopHandler,
|
||||
CheckFn: func() bool { return true },
|
||||
}
|
||||
|
||||
c := NewAvailabilityCacheFromEntry(e, 30*time.Second, 60*time.Second)
|
||||
if !c.Check() {
|
||||
t.Error("expected available")
|
||||
}
|
||||
|
||||
// Nil CheckFn → always available.
|
||||
eNil := ToolEntry{Name: "always", Handler: noopHandler}
|
||||
cNil := NewAvailabilityCacheFromEntry(eNil, 30*time.Second, 60*time.Second)
|
||||
if !cNil.Check() {
|
||||
t.Error("nil CheckFn should mean always available")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAvailabilityCacheConcurrent(t *testing.T) {
|
||||
calls := 0
|
||||
c := NewAvailabilityCache(func() bool {
|
||||
calls++
|
||||
return true
|
||||
}, 10*time.Minute, 10*time.Minute)
|
||||
|
||||
// Concurrent access must not panic.
|
||||
done := make(chan struct{})
|
||||
for range 10 {
|
||||
go func() {
|
||||
for range 100 {
|
||||
c.Check()
|
||||
c.CachedAvailable()
|
||||
c.LastChecked()
|
||||
}
|
||||
done <- struct{}{}
|
||||
}()
|
||||
}
|
||||
|
||||
for range 10 {
|
||||
<-done
|
||||
}
|
||||
|
||||
// At least one call was made (race detector in CI will catch issues).
|
||||
if calls < 1 || calls > 10*100 {
|
||||
t.Errorf("unexpected call count: %d", calls)
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func TestCapPayloadPerResultOnly(t *testing.T) {
|
||||
payload := strings.Repeat("x", 500)
|
||||
tests := []struct {
|
||||
name string
|
||||
limit int
|
||||
spillDir func(*testing.T) string
|
||||
want string
|
||||
}{
|
||||
{name: "disabled", limit: 0, want: payload},
|
||||
{name: "inline truncation", limit: 20, want: "result truncated"},
|
||||
{name: "spill", limit: 20, spillDir: func(t *testing.T) string { return t.TempDir() }, want: "result spilled"},
|
||||
{name: "failed spill falls back", limit: 20, spillDir: func(t *testing.T) string {
|
||||
f, err := os.CreateTemp(t.TempDir(), "blocker")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = f.Close()
|
||||
return filepath.Join(f.Name(), "child")
|
||||
}, want: "result truncated"},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := ""
|
||||
if tc.spillDir != nil {
|
||||
dir = tc.spillDir(t)
|
||||
}
|
||||
got := CapPayload("read", payload, tc.limit, dir)
|
||||
if tc.want == payload {
|
||||
if got != payload {
|
||||
t.Fatalf("got capped payload with disabled limit: %q", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !strings.Contains(got, tc.want) || strings.Contains(got, strings.Repeat("x", 100)) {
|
||||
t.Fatalf("CapPayload() = %q, want compact %q notice", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapPayloadNeverSplitsUTF8(t *testing.T) {
|
||||
payload := strings.Repeat("é", 100)
|
||||
for limit := 1; limit <= 20; limit++ {
|
||||
if got := CapPayload("read", payload, limit, ""); !utf8.ValidString(got) {
|
||||
t.Errorf("limit=%d returned invalid UTF-8: %q", limit, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapPayloadSpillIsPrivateAndUnique(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
first := CapPayload("../../read", strings.Repeat("a", 100), 10, dir)
|
||||
second := CapPayload("../../read", strings.Repeat("b", 100), 10, dir)
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil || len(entries) != 2 {
|
||||
t.Fatalf("spill entries = %v, err = %v", entries, err)
|
||||
}
|
||||
if entries[0].Name() == entries[1].Name() {
|
||||
t.Fatal("spill paths collided")
|
||||
}
|
||||
for _, entry := range entries {
|
||||
info, err := entry.Info()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode().Perm() != 0o600 || strings.Contains(entry.Name(), "..") {
|
||||
t.Fatalf("unsafe spill entry %q mode %o", entry.Name(), info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
if !strings.Contains(first, dir) || !strings.Contains(second, dir) {
|
||||
t.Fatalf("spill references do not name their paths: %q / %q", first, second)
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNonInteractiveBridgeLog(t *testing.T) {
|
||||
var bridge UIBridge = NonInteractiveBridge{}
|
||||
// This will fail to compile until Log is added to UIBridge and NonInteractiveBridge
|
||||
bridge.Log("test chunk")
|
||||
}
|
||||
@@ -1,365 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestApplyEdits(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
content string
|
||||
edits []EditAction
|
||||
want string
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "single edit",
|
||||
content: "func a() {}\nfunc b() {}\n",
|
||||
edits: []EditAction{{OldText: "func a()", NewText: "func alpha()"}},
|
||||
want: "func alpha() {}\nfunc b() {}\n",
|
||||
},
|
||||
{
|
||||
name: "multiple disjoint edits applied against original",
|
||||
content: "one\ntwo\nthree\n",
|
||||
edits: []EditAction{
|
||||
{OldText: "three", NewText: "3"},
|
||||
{OldText: "one", NewText: "1"},
|
||||
},
|
||||
want: "1\ntwo\n3\n",
|
||||
},
|
||||
{
|
||||
name: "replace all",
|
||||
content: "x = a; y = a; z = a\n",
|
||||
edits: []EditAction{{OldText: "a", NewText: "b", ReplaceAll: true}},
|
||||
want: "x = b; y = b; z = b\n",
|
||||
},
|
||||
{
|
||||
name: "not found",
|
||||
content: "hello\n",
|
||||
edits: []EditAction{{OldText: "goodbye", NewText: "farewell"}},
|
||||
wantErr: "old_text not found",
|
||||
},
|
||||
{
|
||||
name: "ambiguous without replace_all",
|
||||
content: "dup\ndup\ndup\n",
|
||||
edits: []EditAction{{OldText: "dup", NewText: "uniq"}},
|
||||
wantErr: "appears 3 times",
|
||||
},
|
||||
{
|
||||
name: "empty old_text",
|
||||
content: "hello\n",
|
||||
edits: []EditAction{{OldText: "", NewText: "x"}},
|
||||
wantErr: "must not be empty",
|
||||
},
|
||||
{
|
||||
name: "identical old and new",
|
||||
content: "hello\n",
|
||||
edits: []EditAction{{OldText: "hello", NewText: "hello"}},
|
||||
wantErr: "identical",
|
||||
},
|
||||
{
|
||||
name: "overlapping edits rejected",
|
||||
content: "abcdef\n",
|
||||
edits: []EditAction{
|
||||
{OldText: "abcd", NewText: "x"},
|
||||
{OldText: "cdef", NewText: "y"},
|
||||
},
|
||||
wantErr: "overlap",
|
||||
},
|
||||
{
|
||||
name: "fuzzy match forgives trailing whitespace in file",
|
||||
content: "line one \nline two\n", // trailing spaces on line one
|
||||
edits: []EditAction{{OldText: "line one\nline two", NewText: "replaced"}},
|
||||
want: "replaced\n",
|
||||
},
|
||||
{
|
||||
name: "fuzzy match forgives trailing whitespace in old_text",
|
||||
content: "line one\nline two\n",
|
||||
edits: []EditAction{{OldText: "line one \nline two", NewText: "replaced"}},
|
||||
want: "replaced\n",
|
||||
},
|
||||
{
|
||||
name: "atomic: second edit failing means no content returned",
|
||||
content: "one\ntwo\n",
|
||||
edits: []EditAction{
|
||||
{OldText: "one", NewText: "1"},
|
||||
{OldText: "missing", NewText: "x"},
|
||||
},
|
||||
wantErr: "edit 2: old_text not found",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, err := applyEdits(tc.content, tc.edits)
|
||||
if tc.wantErr != "" {
|
||||
if err == nil {
|
||||
t.Fatalf("expected error containing %q, got result:\n%s", tc.wantErr, got)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tc.wantErr) {
|
||||
t.Fatalf("expected error containing %q, got: %v", tc.wantErr, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != tc.want {
|
||||
t.Fatalf("result mismatch:\ngot: %q\nwant: %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseEditParams_Quirks(t *testing.T) {
|
||||
t.Run("edits as JSON-encoded string", func(t *testing.T) {
|
||||
params := `{"path": "f.txt", "edits": "[{\"old_text\": \"a\", \"new_text\": \"b\"}]"}`
|
||||
p, err := parseEditParams(json.RawMessage(params))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(p.Edits) != 1 || p.Edits[0].OldText != "a" || p.Edits[0].NewText != "b" {
|
||||
t.Fatalf("unexpected edits: %+v", p.Edits)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("flat old_text and new_text", func(t *testing.T) {
|
||||
params := `{"path": "f.txt", "old_text": "a", "new_text": "b", "replace_all": true}`
|
||||
p, err := parseEditParams(json.RawMessage(params))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(p.Edits) != 1 || p.Edits[0].OldText != "a" || !p.Edits[0].ReplaceAll {
|
||||
t.Fatalf("unexpected edits: %+v", p.Edits)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("canonical form unchanged", func(t *testing.T) {
|
||||
params := `{"path": "f.txt", "edits": [{"old_text": "a", "new_text": "b"}, {"old_text": "c", "new_text": "d"}]}`
|
||||
p, err := parseEditParams(json.RawMessage(params))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(p.Edits) != 2 {
|
||||
t.Fatalf("expected 2 edits, got %+v", p.Edits)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("invalid edits payload errors", func(t *testing.T) {
|
||||
params := `{"path": "f.txt", "edits": "not json"}`
|
||||
if _, err := parseEditParams(json.RawMessage(params)); err == nil {
|
||||
t.Fatal("expected error for undecodable edits")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestEditTool_PreservesCRLFAndBOM(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
path := filepath.Join(tmp, "f.txt")
|
||||
if err := os.WriteFile(path, []byte("\ufefffoo\r\nbar\r\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tool := NewEditTool(tmp, NewMutationQueue(), nil)
|
||||
// old_text uses LF: matching must succeed against the CRLF file.
|
||||
params := `{"path": "f.txt", "edits": [{"old_text": "foo\nbar", "new_text": "baz\nqux"}]}`
|
||||
res, err := tool.Execute(context.Background(), json.RawMessage(params), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if res.IsError {
|
||||
t.Fatalf("unexpected tool error: %s", res.Content)
|
||||
}
|
||||
|
||||
got, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(got) != "\ufeffbaz\r\nqux\r\n" {
|
||||
t.Fatalf("BOM or CRLF not preserved, got: %q", string(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditTool_AtomicOnDisk(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
path := filepath.Join(tmp, "f.txt")
|
||||
original := "one\ntwo\n"
|
||||
if err := os.WriteFile(path, []byte(original), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tool := NewEditTool(tmp, NewMutationQueue(), nil)
|
||||
// First edit is valid, second fails: the file must be left untouched.
|
||||
params := `{"path": "f.txt", "edits": [{"old_text": "one", "new_text": "1"}, {"old_text": "missing", "new_text": "x"}]}`
|
||||
res, err := tool.Execute(context.Background(), json.RawMessage(params), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !res.IsError {
|
||||
t.Fatalf("expected tool error, got: %s", res.Content)
|
||||
}
|
||||
|
||||
got, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(got) != original {
|
||||
t.Fatalf("file was partially modified on failure: %q", string(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditTool_PopulatesDiffDetails(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
path := filepath.Join(tmp, "f.txt")
|
||||
original := "one\ntwo\nthree\n"
|
||||
if err := os.WriteFile(path, []byte(original), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tool := NewEditTool(tmp, NewMutationQueue(), nil)
|
||||
params := `{"path": "f.txt", "edits": [{"old_text": "two", "new_text": "TWO"}]}`
|
||||
res, err := tool.Execute(context.Background(), json.RawMessage(params), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if res.IsError {
|
||||
t.Fatalf("unexpected tool error: %s", res.Content)
|
||||
}
|
||||
|
||||
details, ok := res.Details.(DiffDetails)
|
||||
if !ok {
|
||||
t.Fatalf("expected Details to be a DiffDetails, got %T", res.Details)
|
||||
}
|
||||
if details.OldContent != original {
|
||||
t.Fatalf("OldContent mismatch:\ngot: %q\nwant: %q", details.OldContent, original)
|
||||
}
|
||||
wantNew := "one\nTWO\nthree\n"
|
||||
if details.NewContent != wantNew {
|
||||
t.Fatalf("NewContent mismatch:\ngot: %q\nwant: %q", details.NewContent, wantNew)
|
||||
}
|
||||
if details.Path != path {
|
||||
t.Fatalf("Path mismatch: got %q want %q", details.Path, path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyEdits_ExactMatchPreservesTrailingWhitespace(t *testing.T) {
|
||||
// A single-line old_text is an exact substring match even when the file
|
||||
// line has trailing whitespace, which is preserved around the edit.
|
||||
content := "keep\ntarget \nkeep\n"
|
||||
got, err := applyEdits(content, []EditAction{{OldText: "target", NewText: "T"}})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != "keep\nT \nkeep\n" {
|
||||
t.Fatalf("result mismatch: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The dominant stale_edit cause is indentation drift: the model reproduces the
|
||||
// right code with the wrong leading whitespace. Naming the line and showing the
|
||||
// file's actual text lets the retry succeed without re-reading the file.
|
||||
func TestEdit_NotFoundReportsNearestMatch(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
path := filepath.Join(tmp, "f.go")
|
||||
content := "package p\n\nfunc handleCancel() {\n\t\tdoWork()\n}\n"
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rt := NewReadTracker()
|
||||
rt.MarkRead(tmp, path)
|
||||
tool := NewEditTool(tmp, NewMutationQueue(), rt)
|
||||
|
||||
// Same code, wrong indentation on the body line.
|
||||
res, err := tool.Execute(context.Background(), json.RawMessage(
|
||||
`{"path":"f.go","edits":[{"old_text":"func handleCancel() {\n\tdoWork()\n}","new_text":"func handleCancel() { return }"}]}`,
|
||||
), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !res.IsError {
|
||||
t.Fatal("expected the edit to fail")
|
||||
}
|
||||
if !strings.Contains(res.Content, "line 3") {
|
||||
t.Fatalf("error should name the nearest line, got:\n%s", res.Content)
|
||||
}
|
||||
if !strings.Contains(res.Content, "doWork()") {
|
||||
t.Fatalf("error should show the file's actual text, got:\n%s", res.Content)
|
||||
}
|
||||
|
||||
// The file must be untouched.
|
||||
after, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(after) != content {
|
||||
t.Fatalf("a failed edit must not write; file is now:\n%s", after)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEdit_NotFoundWithNoPlausibleMatchStaysGeneric(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
path := filepath.Join(tmp, "f.go")
|
||||
if err := os.WriteFile(path, []byte("package p\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rt := NewReadTracker()
|
||||
rt.MarkRead(tmp, path)
|
||||
tool := NewEditTool(tmp, NewMutationQueue(), rt)
|
||||
|
||||
res, err := tool.Execute(context.Background(), json.RawMessage(
|
||||
`{"path":"f.go","edits":[{"old_text":"nothing like this exists","new_text":"x"}]}`,
|
||||
), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !res.IsError {
|
||||
t.Fatal("expected the edit to fail")
|
||||
}
|
||||
if strings.Contains(res.Content, "nearest") {
|
||||
t.Fatalf("no plausible match should mean no nearest-match hint, got:\n%s", res.Content)
|
||||
}
|
||||
if !strings.Contains(res.Content, "old_text not found") {
|
||||
t.Fatalf("expected the generic error, got:\n%s", res.Content)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEditToolHonoursDeadlineOnExpiredContext pins the DefaultToolTimeout
|
||||
// contract: when the caller's context is already expired, edit must not
|
||||
// ignore that deadline and mutate the file anyway.
|
||||
func TestEditToolHonoursDeadlineOnExpiredContext(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
path := filepath.Join(tmp, "f.txt")
|
||||
if err := os.WriteFile(path, []byte("hello\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
|
||||
defer cancel()
|
||||
|
||||
tool := NewEditTool(tmp, NewMutationQueue(), nil)
|
||||
res, err := tool.Execute(ctx, json.RawMessage(
|
||||
`{"path":"f.txt","edits":[{"old_text":"hello","new_text":"hi"}]}`,
|
||||
), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !res.IsError {
|
||||
t.Fatalf("edit on an expired context must not succeed; got content %q", res.Content)
|
||||
}
|
||||
|
||||
after, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(after) != "hello\n" {
|
||||
t.Fatalf("file was mutated despite the expired context: %q", after)
|
||||
}
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFindFallback(t *testing.T) {
|
||||
// Create a temporary directory tree.
|
||||
tmp := t.TempDir()
|
||||
createTestFile(t, tmp, "foo.go", "package main")
|
||||
createTestFile(t, tmp, "bar.go", "package bar")
|
||||
createTestFile(t, tmp, "README.md", "# readme")
|
||||
createTestFile(t, tmp, "subdir/baz.go", "package baz")
|
||||
createTestFile(t, tmp, "subdir/nested/deep.txt", "deep")
|
||||
createTestFile(t, tmp, "vendor/mod.go", "package mod")
|
||||
if err := os.MkdirAll(filepath.Join(tmp, "hiddendir"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
createTestFile(t, tmp, "hiddendir/visible.txt", "text")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
params FindParams
|
||||
want []string
|
||||
wantEmpty bool
|
||||
}{
|
||||
{
|
||||
name: "glob pattern *.go (matches all depths)",
|
||||
params: FindParams{Path: tmp, Pattern: "*.go", Type: "file"},
|
||||
want: []string{"bar.go", "foo.go", "subdir/baz.go", "vendor/mod.go"},
|
||||
},
|
||||
{
|
||||
name: "match directories (nested shown)",
|
||||
params: FindParams{Path: tmp, Type: "directory"},
|
||||
want: []string{"hiddendir", "subdir", "subdir/nested", "vendor"},
|
||||
},
|
||||
{
|
||||
name: "max depth 1",
|
||||
params: FindParams{Path: tmp, Type: "file", MaxDepth: 1},
|
||||
want: []string{"bar.go", "foo.go", "README.md"},
|
||||
},
|
||||
{
|
||||
name: "max depth 0 unlimited",
|
||||
params: FindParams{Path: tmp, Type: "file", MaxDepth: 0},
|
||||
want: []string{
|
||||
"bar.go", "foo.go", "README.md",
|
||||
"hiddendir/visible.txt", "subdir/baz.go",
|
||||
"subdir/nested/deep.txt", "vendor/mod.go",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "exclude vendor",
|
||||
params: FindParams{Path: tmp, Type: "file", Exclude: "vendor"},
|
||||
want: []string{
|
||||
"bar.go", "foo.go", "README.md",
|
||||
"hiddendir/visible.txt", "subdir/baz.go",
|
||||
"subdir/nested/deep.txt",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "exclude by glob",
|
||||
params: FindParams{Path: tmp, Type: "file", Exclude: "*.md"},
|
||||
want: []string{
|
||||
"bar.go", "foo.go",
|
||||
"hiddendir/visible.txt", "subdir/baz.go",
|
||||
"subdir/nested/deep.txt", "vendor/mod.go",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "no matches",
|
||||
params: FindParams{Path: tmp, Pattern: "nonexistent*", Type: "file"},
|
||||
wantEmpty: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
res, err := runFindGoFallback(ctx, tmp, tmp, tc.params)
|
||||
if err != nil {
|
||||
t.Fatalf("runFindGoFallback returned error: %v", err)
|
||||
}
|
||||
if tc.wantEmpty {
|
||||
if res.Content != "no matches found" {
|
||||
t.Fatalf("expected empty, got:\n%s", res.Content)
|
||||
}
|
||||
return
|
||||
}
|
||||
gotLines := strings.Split(strings.TrimSpace(res.Content), "\n")
|
||||
if len(gotLines) == 1 && gotLines[0] == "" {
|
||||
gotLines = []string{}
|
||||
}
|
||||
sort.Strings(gotLines)
|
||||
sort.Strings(tc.want)
|
||||
if len(gotLines) != len(tc.want) {
|
||||
t.Fatalf("got %d results, want %d\ngot: %v\nwant: %v", len(gotLines), len(tc.want), gotLines, tc.want)
|
||||
}
|
||||
for i := range tc.want {
|
||||
if gotLines[i] != tc.want[i] {
|
||||
t.Fatalf("result mismatch at %d: got %q, want %q", i, gotLines[i], tc.want[i])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindFallback_NonExistentPath(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
res, _ := runFindGoFallback(ctx, "/nonexistent/path", "/nonexistent/path", FindParams{})
|
||||
if !res.IsError {
|
||||
t.Fatal("expected error for non-existent path")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindFallback_NotADirectory(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
f := filepath.Join(tmp, "file.txt")
|
||||
if err := os.WriteFile(f, []byte("hello"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
res, _ := runFindGoFallback(ctx, tmp, f, FindParams{})
|
||||
if !res.IsError {
|
||||
t.Fatal("expected error when path is a file")
|
||||
}
|
||||
}
|
||||
|
||||
// A cancelled or timed-out walk must be reported as an error, not silently
|
||||
// returned as "no matches found" (or as whatever partial results happened to
|
||||
// accumulate before cancellation). The WalkDir callback swallows every
|
||||
// per-entry error and returns nil, so the only error that can ever reach the
|
||||
// caller is ctx.Err() from the cancellation select -- the old guard compared
|
||||
// that against itself and never fired.
|
||||
func TestFindFallback_CancelledWalkReportsError(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
createTestFile(t, tmp, "foo.go", "package main")
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
res, err := runFindGoFallback(ctx, tmp, tmp, FindParams{})
|
||||
if err != nil {
|
||||
t.Fatalf("runFindGoFallback returned an error: %v", err)
|
||||
}
|
||||
if !res.IsError {
|
||||
t.Fatalf("expected an error result for a cancelled walk, got: %q", res.Content)
|
||||
}
|
||||
if res.Content == "no matches found" {
|
||||
t.Fatal("cancelled walk reported as 'no matches found': the search never finished")
|
||||
}
|
||||
}
|
||||
|
||||
func createTestFile(t *testing.T, base, relPath, content string) {
|
||||
t.Helper()
|
||||
full := filepath.Join(base, relPath)
|
||||
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(full, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRunWithContext_ReturnsFnResult(t *testing.T) {
|
||||
err := runWithContext(context.Background(), func() error { return nil })
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
sentinel := errors.New("boom")
|
||||
err = runWithContext(context.Background(), func() error { return sentinel })
|
||||
if !errors.Is(err, sentinel) {
|
||||
t.Fatalf("expected sentinel error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunWithContext_ReturnsCtxErrOnAlreadyExpired verifies that when the
|
||||
// context is already done before runWithContext is called, no goroutine is
|
||||
// spawned and the context error is returned immediately.
|
||||
func TestRunWithContext_ReturnsCtxErrOnAlreadyExpired(t *testing.T) {
|
||||
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
|
||||
defer cancel()
|
||||
|
||||
spawned := make(chan struct{})
|
||||
err := runWithContext(ctx, func() error {
|
||||
close(spawned)
|
||||
return nil
|
||||
})
|
||||
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("expected context.DeadlineExceeded, got %v", err)
|
||||
}
|
||||
|
||||
// The goroutine must NOT have been spawned because the context
|
||||
// was already expired. Give it a short grace period to prove the
|
||||
// negative.
|
||||
select {
|
||||
case <-spawned:
|
||||
t.Fatal("fn was spawned even though the context was already expired — goroutine leak")
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
// Expected: fn was never called.
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunWithContext_ReturnsCtxErrOnTimeout is the core regression coverage
|
||||
// for tau-6wa: fn blocks forever (simulating a hung filesystem call); the
|
||||
// caller must get control back once ctx expires rather than waiting for fn.
|
||||
func TestRunWithContext_ReturnsCtxErrOnTimeout(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
fnStarted := make(chan struct{})
|
||||
blockForever := make(chan struct{}) // deliberately never closed
|
||||
|
||||
start := time.Now()
|
||||
err := runWithContext(ctx, func() error {
|
||||
close(fnStarted)
|
||||
<-blockForever
|
||||
return nil
|
||||
})
|
||||
elapsed := time.Since(start)
|
||||
|
||||
<-fnStarted // make sure fn actually started (and is now hung) before checking the result
|
||||
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("expected context.DeadlineExceeded, got %v", err)
|
||||
}
|
||||
if elapsed > 500*time.Millisecond {
|
||||
t.Fatalf("runWithContext took %v to return after the deadline, expected it to return promptly instead of waiting on the hung fn", elapsed)
|
||||
}
|
||||
}
|
||||
@@ -1,329 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestGrepReportsSearchFailureRatherThanNoMatches guards the distinction
|
||||
// between ripgrep's exit 1 (no matches) and exit 2 (the search never ran). An
|
||||
// errorlint autofix once rewrote the check to match any *exec.ExitError and
|
||||
// dropped the exit code, which reported a failed search as an empty result --
|
||||
// the model would then state that a file contains nothing on the strength of a
|
||||
// search that never happened. An unterminated group is a parse error, so
|
||||
// ripgrep exits 2 here.
|
||||
func TestGrepReportsSearchFailureRatherThanNoMatches(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
createGrepTestFile(t, tmp, "haystack.txt", "needle\n")
|
||||
tool := NewGrepTool(tmp)
|
||||
|
||||
result, err := tool.Execute(context.Background(), json.RawMessage(`{"pattern":"(unclosed"}`), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
if !result.IsError {
|
||||
t.Fatalf("a failed search must be reported as an error, got %#v", result)
|
||||
}
|
||||
if strings.Contains(result.Content, "no matches found") {
|
||||
t.Fatalf("a failed search was reported as an empty result: %s", result.Content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGrepFallback(t *testing.T) {
|
||||
// Create a temporary directory with test files.
|
||||
tmp := t.TempDir()
|
||||
createGrepTestFile(t, tmp, "alpha.go", "package alpha\nfunc Hello() {}\n")
|
||||
createGrepTestFile(t, tmp, "beta.go", "package beta\nfunc World() {}\nfunc hello() {}\n")
|
||||
createGrepTestFile(t, tmp, "gamma.txt", "Hello world\n")
|
||||
createGrepTestFile(t, tmp, "vendor/mod.go", "package vendor\nfunc Hello() {}\n")
|
||||
createGrepTestFile(t, tmp, "subdir/nested.go", "package nested\nfunc HelloThere() {}\n")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
params GrepParams
|
||||
want []string
|
||||
wantEmpty bool
|
||||
}{
|
||||
{
|
||||
name: "literal match in file",
|
||||
params: GrepParams{Pattern: "Hello", Path: filepath.Join(tmp, "alpha.go")},
|
||||
want: []string{"alpha.go:2:func Hello() {}"},
|
||||
},
|
||||
{
|
||||
// Smart case: an uppercase letter in the pattern makes the
|
||||
// search case-sensitive, matching ripgrep's --smart-case.
|
||||
name: "match in directory (smart case)",
|
||||
params: GrepParams{Pattern: "Hello", Path: tmp},
|
||||
want: []string{
|
||||
"alpha.go:2:func Hello() {}",
|
||||
"gamma.txt:1:Hello world",
|
||||
"subdir/nested.go:2:func HelloThere() {}",
|
||||
"vendor/mod.go:2:func Hello() {}",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "lowercase pattern matches both cases",
|
||||
params: GrepParams{Pattern: "hello", Path: tmp},
|
||||
want: []string{
|
||||
"alpha.go:2:func Hello() {}",
|
||||
"beta.go:3:func hello() {}",
|
||||
"gamma.txt:1:Hello world",
|
||||
"subdir/nested.go:2:func HelloThere() {}",
|
||||
"vendor/mod.go:2:func Hello() {}",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "case sensitive literal",
|
||||
params: GrepParams{Pattern: "Hello", Path: tmp, CaseSensitive: true},
|
||||
want: []string{
|
||||
"alpha.go:2:func Hello() {}",
|
||||
"gamma.txt:1:Hello world",
|
||||
"subdir/nested.go:2:func HelloThere() {}",
|
||||
"vendor/mod.go:2:func Hello() {}",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "regex match by default",
|
||||
params: GrepParams{Pattern: "Hello.*", Path: tmp},
|
||||
want: []string{
|
||||
"alpha.go:2:func Hello() {}",
|
||||
"gamma.txt:1:Hello world",
|
||||
"subdir/nested.go:2:func HelloThere() {}",
|
||||
"vendor/mod.go:2:func Hello() {}",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "regex alternation",
|
||||
params: GrepParams{Pattern: "World|world", Path: tmp},
|
||||
want: []string{
|
||||
"beta.go:2:func World() {}",
|
||||
"gamma.txt:1:Hello world",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "literal match with regex metacharacters",
|
||||
params: GrepParams{Pattern: "Hello() {}", Path: tmp, Literal: true, CaseSensitive: true},
|
||||
want: []string{
|
||||
"alpha.go:2:func Hello() {}",
|
||||
"vendor/mod.go:2:func Hello() {}",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "include filter",
|
||||
params: GrepParams{Pattern: "hello", Path: tmp, Include: "*.go"},
|
||||
want: []string{
|
||||
"alpha.go:2:func Hello() {}",
|
||||
"beta.go:3:func hello() {}",
|
||||
"subdir/nested.go:2:func HelloThere() {}",
|
||||
"vendor/mod.go:2:func Hello() {}",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "context lines",
|
||||
params: GrepParams{Pattern: "Hello", Path: filepath.Join(tmp, "alpha.go"), ContextBefore: 1, ContextAfter: 1},
|
||||
want: []string{
|
||||
"alpha.go-1-package alpha",
|
||||
"alpha.go:2:func Hello() {}",
|
||||
"alpha.go-3-", // trailing newline yields empty third line
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "no matches",
|
||||
params: GrepParams{Pattern: "nonexistentXYZ", Path: tmp},
|
||||
wantEmpty: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, err := grepFallback(ctx, tc.params, tc.params.Path, tmp)
|
||||
if err != nil {
|
||||
t.Fatalf("grepFallback error: %v", err)
|
||||
}
|
||||
if tc.wantEmpty {
|
||||
if got != "" {
|
||||
t.Fatalf("expected empty, got:\n%s", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
gotLines := strings.Split(strings.TrimSpace(got), "\n")
|
||||
if len(gotLines) == 1 && gotLines[0] == "" {
|
||||
gotLines = []string{}
|
||||
}
|
||||
if len(gotLines) != len(tc.want) {
|
||||
t.Fatalf("got %d results, want %d\ngot:\n%s\nwant: %v", len(gotLines), len(tc.want), got, tc.want)
|
||||
}
|
||||
for i := range tc.want {
|
||||
if gotLines[i] != tc.want[i] {
|
||||
t.Fatalf("result mismatch at %d: got %q, want %q", i, gotLines[i], tc.want[i])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGrepFallback_ContextDedup(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
content := "line1\nHello\nline3\nHello\nline5\n"
|
||||
createGrepTestFile(t, tmp, "test.txt", content)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
params := GrepParams{Pattern: "Hello", Path: tmp, ContextBefore: 1, ContextAfter: 1}
|
||||
got, err := grepFallback(ctx, params, tmp, tmp)
|
||||
if err != nil {
|
||||
t.Fatalf("grepFallback error: %v", err)
|
||||
}
|
||||
|
||||
lines := strings.Split(strings.TrimSpace(got), "\n")
|
||||
// Expected:
|
||||
// line1 (context for first Hello)
|
||||
// Hello (match 1)
|
||||
// line3 (context after first Hello + context before second Hello - dedup)
|
||||
// Hello (match 2)
|
||||
// line5 (context after second Hello)
|
||||
// Total unique lines: 5
|
||||
if len(lines) != 5 {
|
||||
t.Fatalf("expected 5 lines, got %d:\n%s", len(lines), got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapGrepOutput_MatchLimit(t *testing.T) {
|
||||
var lines []string
|
||||
for i := 1; i <= 20; i++ {
|
||||
lines = append(lines, fmt.Sprintf("file.go:%d:match line", i))
|
||||
}
|
||||
output := strings.Join(lines, "\n")
|
||||
|
||||
got := capGrepResult(output, 5).Content
|
||||
|
||||
if !strings.Contains(got, "[showing first 5 matches") {
|
||||
t.Fatalf("expected match-limit notice, got:\n%s", got)
|
||||
}
|
||||
matchCount := strings.Count(got, "match line")
|
||||
if matchCount != 5 {
|
||||
t.Fatalf("expected 5 match lines, got %d", matchCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapGrepOutput_LongLines(t *testing.T) {
|
||||
long := "file.js:1:" + strings.Repeat("x", 2000)
|
||||
got := capGrepResult(long, 100).Content
|
||||
|
||||
if !strings.Contains(got, "... [truncated]") {
|
||||
t.Fatalf("expected per-line truncation marker, got:\n%s", got)
|
||||
}
|
||||
if !strings.Contains(got, "[some lines truncated to 500 chars]") {
|
||||
t.Fatalf("expected long-line notice, got:\n%s", got)
|
||||
}
|
||||
if len(strings.Split(got, "\n")[0]) > 600 {
|
||||
t.Fatalf("first line not capped: %d chars", len(strings.Split(got, "\n")[0]))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapGrepOutput_ContextLinesNotCounted(t *testing.T) {
|
||||
// Context lines (dash separators) must not count towards the match limit.
|
||||
output := strings.Join([]string{
|
||||
"file.go-1-context before",
|
||||
"file.go:2:match one",
|
||||
"file.go-3-context after",
|
||||
"file.go:4:match two",
|
||||
}, "\n")
|
||||
|
||||
got := capGrepResult(output, 2).Content
|
||||
|
||||
if strings.Contains(got, "[showing first") {
|
||||
t.Fatalf("limit notice should not fire for 2 matches with limit 2, got:\n%s", got)
|
||||
}
|
||||
if !strings.Contains(got, "match two") {
|
||||
t.Fatalf("expected both matches present, got:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGrepFallback_NonExistentPath(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err := grepFallback(ctx, GrepParams{Pattern: "foo"}, "/nonexistent/path", "/nonexistent/path")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for non-existent path")
|
||||
}
|
||||
}
|
||||
|
||||
func createGrepTestFile(t *testing.T, base, relPath, content string) {
|
||||
t.Helper()
|
||||
full := filepath.Join(base, relPath)
|
||||
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(full, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGrepClampsContextLines(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
var lines []string
|
||||
for i := 1; i <= 200; i++ {
|
||||
if i == 100 {
|
||||
lines = append(lines, "the needle")
|
||||
continue
|
||||
}
|
||||
lines = append(lines, fmt.Sprintf("filler %d", i))
|
||||
}
|
||||
createGrepTestFile(t, tmp, "f.txt", strings.Join(lines, "\n")+"\n")
|
||||
|
||||
tool := NewGrepTool(tmp)
|
||||
res, err := tool.Execute(context.Background(), json.RawMessage(
|
||||
`{"pattern":"needle","context_before":40,"context_after":40}`,
|
||||
), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if res.IsError {
|
||||
t.Fatalf("unexpected tool error: %s", res.Content)
|
||||
}
|
||||
|
||||
// Context is clamped to grepMaxContext either side, so a line that far
|
||||
// from the match must not appear.
|
||||
if strings.Contains(res.Content, "filler 80") || strings.Contains(res.Content, "filler 120") {
|
||||
t.Fatalf("context lines were not clamped, got:\n%s", res.Content)
|
||||
}
|
||||
if !strings.Contains(res.Content, "filler 99") || !strings.Contains(res.Content, "filler 101") {
|
||||
t.Fatalf("clamped context should still include adjacent lines, got:\n%s", res.Content)
|
||||
}
|
||||
if !strings.Contains(res.Content, "context") {
|
||||
t.Fatalf("expected a notice explaining the clamp, got:\n%s", res.Content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGrepLeavesModestContextAlone(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
createGrepTestFile(t, tmp, "f.txt", "a\nb\nneedle\nd\ne\n")
|
||||
|
||||
tool := NewGrepTool(tmp)
|
||||
res, err := tool.Execute(context.Background(), json.RawMessage(
|
||||
`{"pattern":"needle","context_before":2,"context_after":2}`,
|
||||
), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if strings.Contains(res.Content, "clamped") {
|
||||
t.Fatalf("a within-limit request must not be clamped, got:\n%s", res.Content)
|
||||
}
|
||||
for _, want := range []string{"a", "b", "needle", "d", "e"} {
|
||||
if !strings.Contains(res.Content, want) {
|
||||
t.Fatalf("missing %q in:\n%s", want, res.Content)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
package builtin_test
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools/builtin"
|
||||
)
|
||||
|
||||
func TestMutationQueue_Serializes(t *testing.T) {
|
||||
q := builtin.NewMutationQueue()
|
||||
path := "/tmp/test.txt"
|
||||
|
||||
var counter atomic.Int64
|
||||
var maxConcurrent atomic.Int64
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for i := range 50 {
|
||||
_ = i
|
||||
wg.Go(func() {
|
||||
release := q.Acquire(path)
|
||||
defer release()
|
||||
|
||||
cur := counter.Add(1)
|
||||
// Track max concurrency for this path.
|
||||
for {
|
||||
old := maxConcurrent.Load()
|
||||
if cur <= old || maxConcurrent.CompareAndSwap(old, cur) {
|
||||
break
|
||||
}
|
||||
}
|
||||
counter.Add(-1)
|
||||
})
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
if maxConcurrent.Load() > 1 {
|
||||
t.Fatalf("expected max concurrency of 1, got %d", maxConcurrent.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestMutationQueue_DifferentPaths_Parallel(t *testing.T) {
|
||||
q := builtin.NewMutationQueue()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
started := make(chan struct{}, 2)
|
||||
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
release := q.Acquire("/path/a")
|
||||
started <- struct{}{}
|
||||
<-started // wait for both to acquire
|
||||
release()
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
release := q.Acquire("/path/b")
|
||||
started <- struct{}{}
|
||||
<-started // wait for both to acquire
|
||||
release()
|
||||
}()
|
||||
|
||||
wg.Wait()
|
||||
// If we get here without deadlocking, different paths don't block each other.
|
||||
}
|
||||
@@ -1,227 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestPathConfinementToggle covers the escape hatch for deployments where the
|
||||
// agent is a general-purpose operator rather than a coding assistant scoped to
|
||||
// one project -- formatting and mounting a new disk, migrating data between
|
||||
// filesystems, editing service units. Confining those to one directory makes
|
||||
// the agent useless, so the jail has to be switchable.
|
||||
//
|
||||
// Not parallel: the toggle is process-wide.
|
||||
func TestPathConfinementToggle(t *testing.T) {
|
||||
const workspace = "/home/sam"
|
||||
outside := []string{"/etc/fstab", "/mnt/newdisk/data", "/srv"}
|
||||
|
||||
t.Run("confined by default", func(t *testing.T) {
|
||||
for _, target := range outside {
|
||||
if isConfined(workspace, target) {
|
||||
t.Errorf("isConfined(%q, %q) = true, want false by default", workspace, target)
|
||||
}
|
||||
if isReadConfined(workspace, target) {
|
||||
t.Errorf("isReadConfined(%q, %q) = true, want false by default", workspace, target)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("unconfined when disabled", func(t *testing.T) {
|
||||
SetPathConfinement(false)
|
||||
t.Cleanup(func() { SetPathConfinement(true) })
|
||||
|
||||
for _, target := range outside {
|
||||
if !isConfined(workspace, target) {
|
||||
t.Errorf("isConfined(%q, %q) = false with confinement disabled", workspace, target)
|
||||
}
|
||||
if !isReadConfined(workspace, target) {
|
||||
t.Errorf("isReadConfined(%q, %q) = false with confinement disabled", workspace, target)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("restored after re-enabling", func(t *testing.T) {
|
||||
if isConfined(workspace, "/etc/fstab") {
|
||||
t.Error("confinement did not come back after being re-enabled")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestResolvePathUnaffectedByConfinement pins the property that makes the
|
||||
// toggle safe to flip: relative paths stay rooted at the workspace either way,
|
||||
// so turning the jail off widens what an ABSOLUTE path can reach without
|
||||
// silently changing where a relative one lands.
|
||||
func TestResolvePathUnaffectedByConfinement(t *testing.T) {
|
||||
SetPathConfinement(false)
|
||||
t.Cleanup(func() { SetPathConfinement(true) })
|
||||
|
||||
if got := resolvePath("/home/sam", "notes.md"); got != "/home/sam/notes.md" {
|
||||
t.Errorf("resolvePath relative = %q, want it still rooted at the workspace", got)
|
||||
}
|
||||
if got := resolvePath("/home/sam", "/etc/fstab"); got != "/etc/fstab" {
|
||||
t.Errorf("resolvePath absolute = %q, want it untouched", got)
|
||||
}
|
||||
}
|
||||
|
||||
// withGoModCache points the module-cache lookup at a temp dir for the duration
|
||||
// of a test, so these tests never depend on the host's real GOMODCACHE.
|
||||
func withGoModCache(t *testing.T, dir string) {
|
||||
t.Helper()
|
||||
prev := goModCacheDir
|
||||
goModCacheDir = func() string { return dir }
|
||||
t.Cleanup(func() { goModCacheDir = prev })
|
||||
}
|
||||
|
||||
func TestReadAllowsGoModCache(t *testing.T) {
|
||||
cwd := t.TempDir()
|
||||
cache := t.TempDir()
|
||||
withGoModCache(t, cache)
|
||||
|
||||
dep := filepath.Join(cache, "example.com", "dep@v1.0.0")
|
||||
if err := os.MkdirAll(dep, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dep, "dep.go"), []byte("package dep\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
res := execRead(t, cwd, `{"path":`+quote(filepath.Join(dep, "dep.go"))+`}`)
|
||||
if res.IsError {
|
||||
t.Fatalf("expected read of a module-cache file to succeed, got: %s", res.Content)
|
||||
}
|
||||
if !strings.Contains(res.Content, "package dep") {
|
||||
t.Fatalf("unexpected content: %s", res.Content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGrepRejectsGoModCache(t *testing.T) {
|
||||
cwd := t.TempDir()
|
||||
cache := t.TempDir()
|
||||
withGoModCache(t, cache)
|
||||
|
||||
if err := os.WriteFile(filepath.Join(cache, "dep.go"), []byte("package dep\nfunc Needle() {}\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tool := NewGrepTool(cwd)
|
||||
res, err := tool.Execute(context.Background(), json.RawMessage(
|
||||
`{"pattern":"Needle","path":`+quote(cache)+`}`,
|
||||
), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !res.IsError || !strings.Contains(res.Content, "escapes working directory") {
|
||||
t.Fatalf("expected grep of the module cache to be rejected, got: %#v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindRejectsOutsideWorkspace(t *testing.T) {
|
||||
cwd := t.TempDir()
|
||||
cache := t.TempDir()
|
||||
other := t.TempDir()
|
||||
withGoModCache(t, cache)
|
||||
|
||||
if err := os.MkdirAll(filepath.Join(cache, "example.com", "dep@v1.0.0"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(other, "main.go"), []byte("package main\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tool := NewFindTool(cwd)
|
||||
for _, path := range []string{cache, other, "/home/sam"} {
|
||||
res, err := tool.Execute(context.Background(), json.RawMessage(`{"path":`+quote(path)+`}`), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("path %s: unexpected error: %v", path, err)
|
||||
}
|
||||
if !res.IsError || !strings.Contains(res.Content, "escapes working directory") {
|
||||
t.Fatalf("path %s: expected workspace-confined find, got: %#v", path, res)
|
||||
}
|
||||
}
|
||||
|
||||
inside := filepath.Join(cwd, "keep.go")
|
||||
if err := os.WriteFile(inside, []byte("package keep\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res, err := tool.Execute(context.Background(), json.RawMessage(`{"pattern":"keep.go"}`), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.IsError || !strings.Contains(res.Content, "keep.go") {
|
||||
t.Fatalf("expected workspace find to succeed, got: %#v", res)
|
||||
}
|
||||
}
|
||||
|
||||
// The module cache is a read-only escape hatch. Mutating tools must still be
|
||||
// confined to the workspace, or the agent could corrupt shared dependencies.
|
||||
func TestWriteRejectsGoModCache(t *testing.T) {
|
||||
cwd := t.TempDir()
|
||||
cache := t.TempDir()
|
||||
withGoModCache(t, cache)
|
||||
|
||||
tool := NewWriteTool(cwd, nil, NewReadTracker())
|
||||
res, err := tool.Execute(context.Background(), json.RawMessage(
|
||||
`{"path":`+quote(filepath.Join(cache, "evil.go"))+`,"content":"package evil\n"}`,
|
||||
), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !res.IsError || !strings.Contains(res.Content, "escapes working directory") {
|
||||
t.Fatalf("expected write to the module cache to be rejected, got: %#v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditRejectsGoModCache(t *testing.T) {
|
||||
cwd := t.TempDir()
|
||||
cache := t.TempDir()
|
||||
withGoModCache(t, cache)
|
||||
|
||||
target := filepath.Join(cache, "dep.go")
|
||||
if err := os.WriteFile(target, []byte("package dep\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rt := NewReadTracker()
|
||||
rt.MarkRead(cwd, target)
|
||||
tool := NewEditTool(cwd, nil, rt)
|
||||
res, err := tool.Execute(context.Background(), json.RawMessage(
|
||||
`{"path":`+quote(target)+`,"edits":[{"old_text":"package dep","new_text":"package hacked"}]}`,
|
||||
), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !res.IsError || !strings.Contains(res.Content, "escapes working directory") {
|
||||
t.Fatalf("expected edit of the module cache to be rejected, got: %#v", res)
|
||||
}
|
||||
}
|
||||
|
||||
// A path in neither the workspace nor the module cache stays rejected.
|
||||
func TestReadRejectsUnrelatedAbsolutePath(t *testing.T) {
|
||||
cwd := t.TempDir()
|
||||
cache := t.TempDir()
|
||||
other := t.TempDir()
|
||||
withGoModCache(t, cache)
|
||||
|
||||
target := filepath.Join(other, "secret.txt")
|
||||
if err := os.WriteFile(target, []byte("secret\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
res := execRead(t, cwd, `{"path":`+quote(target)+`}`)
|
||||
if !res.IsError || !strings.Contains(res.Content, "escapes working directory") {
|
||||
t.Fatalf("expected an unrelated absolute path to be rejected, got: %#v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func quote(s string) string {
|
||||
b, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// bigGoFile builds a Go file well past the outline threshold, with each
|
||||
// function body padded so bodies dominate the byte count.
|
||||
func bigGoFile(t *testing.T, dir, name string, funcs int) {
|
||||
t.Helper()
|
||||
var b strings.Builder
|
||||
b.WriteString("package big\n\nimport \"fmt\"\n\n")
|
||||
for i := range funcs {
|
||||
fmt.Fprintf(&b, "// Doc for Fn%d.\nfunc Fn%d() {\n", i, i)
|
||||
for j := range 20 {
|
||||
fmt.Fprintf(&b, "\tfmt.Println(\"body %d line %d\")\n", i, j)
|
||||
}
|
||||
b.WriteString("}\n\n")
|
||||
}
|
||||
writeReadTestFile(t, dir, name, b.String())
|
||||
}
|
||||
|
||||
func TestRead_LargeGoFileReturnsOutline(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
bigGoFile(t, tmp, "big.go", 60)
|
||||
|
||||
res := execRead(t, tmp, `{"path":"big.go"}`)
|
||||
if res.IsError {
|
||||
t.Fatalf("unexpected tool error: %s", res.Content)
|
||||
}
|
||||
if !strings.Contains(res.Content, "func Fn0()") || !strings.Contains(res.Content, "func Fn59()") {
|
||||
t.Fatalf("outline should span the whole file, got:\n%s", truncateForMsg(res.Content))
|
||||
}
|
||||
if strings.Contains(res.Content, "body 0 line 0") {
|
||||
t.Fatalf("outline must not include function bodies, got:\n%s", truncateForMsg(res.Content))
|
||||
}
|
||||
if !strings.Contains(res.Content, "offset") {
|
||||
t.Fatalf("outline must tell the model how to read a range, got:\n%s", truncateForMsg(res.Content))
|
||||
}
|
||||
}
|
||||
|
||||
// Line numbers are the whole point: without them the outline is not actionable.
|
||||
func TestRead_OutlineCarriesLineNumbers(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
bigGoFile(t, tmp, "big.go", 60)
|
||||
|
||||
res := execRead(t, tmp, `{"path":"big.go"}`)
|
||||
// Each Fn is preceded by a doc comment, so blocks are 24 lines apart
|
||||
// starting at line 6. Assert the mapping is real rather than just present.
|
||||
for _, want := range []string{"6: func Fn0()", "30: func Fn1()"} {
|
||||
if !strings.Contains(res.Content, want) {
|
||||
t.Fatalf("expected outline entry %q, got:\n%s", want, truncateForMsg(res.Content))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRead_ExplicitRangeBypassesOutline(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
bigGoFile(t, tmp, "big.go", 60)
|
||||
|
||||
res := execRead(t, tmp, `{"path":"big.go","offset":6,"limit":3}`)
|
||||
if !strings.Contains(res.Content, "body 0 line 0") {
|
||||
t.Fatalf("an explicit range must return raw content, got:\n%s", truncateForMsg(res.Content))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRead_FullBypassesOutline(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
bigGoFile(t, tmp, "big.go", 60)
|
||||
|
||||
res := execRead(t, tmp, `{"path":"big.go","full":true}`)
|
||||
if !strings.Contains(res.Content, "body 0 line 0") {
|
||||
t.Fatalf("full:true must return raw content, got:\n%s", truncateForMsg(res.Content))
|
||||
}
|
||||
}
|
||||
|
||||
// Files at or below the normal read budget must behave exactly as before.
|
||||
func TestRead_SmallGoFileIsUnaffected(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
bigGoFile(t, tmp, "small.go", 3)
|
||||
|
||||
res := execRead(t, tmp, `{"path":"small.go"}`)
|
||||
if !strings.Contains(res.Content, "body 0 line 0") {
|
||||
t.Fatalf("a small file must return raw content, got:\n%s", truncateForMsg(res.Content))
|
||||
}
|
||||
}
|
||||
|
||||
// An unrecognised language has no reliable declaration pattern, so outlining
|
||||
// would risk returning an arbitrary subset of lines as if it were structure.
|
||||
func TestRead_LargeUnknownFileTypeIsUnaffected(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
var b strings.Builder
|
||||
for i := range 2000 {
|
||||
fmt.Fprintf(&b, "arbitrary line %d\n", i)
|
||||
}
|
||||
writeReadTestFile(t, tmp, "data.unknownext", b.String())
|
||||
|
||||
res := execRead(t, tmp, `{"path":"data.unknownext"}`)
|
||||
if !strings.Contains(res.Content, "arbitrary line 0") {
|
||||
t.Fatalf("an unknown file type must fall back to raw content, got:\n%s", truncateForMsg(res.Content))
|
||||
}
|
||||
}
|
||||
|
||||
// A large source file with no recognisable declarations (generated tables,
|
||||
// embedded data) must not collapse to an empty outline.
|
||||
func TestRead_LargeGoFileWithoutDeclarationsIsUnaffected(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
var b strings.Builder
|
||||
b.WriteString("package gen\n")
|
||||
for i := range 2000 {
|
||||
fmt.Fprintf(&b, "\t\"key%d\": %d,\n", i, i)
|
||||
}
|
||||
writeReadTestFile(t, tmp, "table.go", b.String())
|
||||
|
||||
res := execRead(t, tmp, `{"path":"table.go"}`)
|
||||
if !strings.Contains(res.Content, `"key0"`) {
|
||||
t.Fatalf("a file with no declarations must fall back to raw content, got:\n%s", truncateForMsg(res.Content))
|
||||
}
|
||||
}
|
||||
|
||||
func truncateForMsg(s string) string {
|
||||
if len(s) > 600 {
|
||||
return s[:600] + "..."
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// An explicit limit that happens to equal the default is still explicit, and
|
||||
// must be honoured as a content request rather than read as "unspecified".
|
||||
func TestRead_ExplicitDefaultSizedLimitBypassesOutline(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
bigGoFile(t, tmp, "big.go", 60)
|
||||
|
||||
res := execRead(t, tmp, fmt.Sprintf(`{"path":"big.go","limit":%d}`, DefaultReadLines))
|
||||
if !strings.Contains(res.Content, "body 0 line 0") {
|
||||
t.Fatalf("an explicit limit must return raw content, got:\n%s", truncateForMsg(res.Content))
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func numberedFile(t *testing.T, dir, name string, n int) string {
|
||||
t.Helper()
|
||||
lines := make([]string, n)
|
||||
for i := range lines {
|
||||
lines[i] = fmt.Sprintf("line %d", i+1)
|
||||
}
|
||||
writeReadTestFile(t, dir, name, strings.Join(lines, "\n"))
|
||||
return filepath.Join(dir, name)
|
||||
}
|
||||
|
||||
// readTwice runs the read tool twice through one tracker, as a session would.
|
||||
func readTwice(t *testing.T, cwd, first, second string) (Result, Result) {
|
||||
t.Helper()
|
||||
tool := NewReadTool(cwd, NewReadTracker())
|
||||
r1, err := tool.Execute(context.Background(), json.RawMessage(first), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("first read: %v", err)
|
||||
}
|
||||
r2, err := tool.Execute(context.Background(), json.RawMessage(second), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("second read: %v", err)
|
||||
}
|
||||
return r1, r2
|
||||
}
|
||||
|
||||
func TestRead_UnchangedRepeatIsSuppressed(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
numberedFile(t, tmp, "f.txt", 50)
|
||||
|
||||
r1, r2 := readTwice(t, tmp, `{"path":"f.txt"}`, `{"path":"f.txt"}`)
|
||||
if r1.IsError || !strings.Contains(r1.Content, "line 50") {
|
||||
t.Fatalf("first read should return the body, got: %s", r1.Content)
|
||||
}
|
||||
if r2.IsError {
|
||||
t.Fatalf("second read errored: %s", r2.Content)
|
||||
}
|
||||
if strings.Contains(r2.Content, "line 50") {
|
||||
t.Fatalf("second read should not resend the body, got:\n%s", r2.Content)
|
||||
}
|
||||
if !strings.Contains(r2.Content, "unchanged") {
|
||||
t.Fatalf("second read should say the file is unchanged, got:\n%s", r2.Content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRead_ChangedFileIsResent(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
path := numberedFile(t, tmp, "f.txt", 20)
|
||||
|
||||
tool := NewReadTool(tmp, NewReadTracker())
|
||||
if _, err := tool.Execute(context.Background(), json.RawMessage(`{"path":"f.txt"}`), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Rewrite with different content and a distinct mtime.
|
||||
if err := os.WriteFile(path, []byte("totally different\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chtimes(path, time.Now().Add(time.Second), time.Now().Add(time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
res, err := tool.Execute(context.Background(), json.RawMessage(`{"path":"f.txt"}`), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(res.Content, "totally different") {
|
||||
t.Fatalf("a changed file must be resent in full, got:\n%s", res.Content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRead_OverlappingRangeReturnsOnlyNovelLines(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
numberedFile(t, tmp, "f.txt", 300)
|
||||
|
||||
_, r2 := readTwice(t, tmp,
|
||||
`{"path":"f.txt","offset":1,"limit":100}`,
|
||||
`{"path":"f.txt","offset":1,"limit":200}`)
|
||||
|
||||
if r2.IsError {
|
||||
t.Fatalf("second read errored: %s", r2.Content)
|
||||
}
|
||||
if strings.Contains(r2.Content, "line 50\n") {
|
||||
t.Fatalf("already-served lines were resent, got:\n%s", r2.Content)
|
||||
}
|
||||
if !strings.Contains(r2.Content, "line 101") || !strings.Contains(r2.Content, "line 200") {
|
||||
t.Fatalf("novel lines 101-200 missing, got:\n%s", r2.Content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRead_DisjointRangeIsServedNormally(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
numberedFile(t, tmp, "f.txt", 300)
|
||||
|
||||
_, r2 := readTwice(t, tmp,
|
||||
`{"path":"f.txt","offset":1,"limit":50}`,
|
||||
`{"path":"f.txt","offset":200,"limit":50}`)
|
||||
|
||||
if r2.IsError {
|
||||
t.Fatalf("second read errored: %s", r2.Content)
|
||||
}
|
||||
if !strings.Contains(r2.Content, "line 200") || !strings.Contains(r2.Content, "line 249") {
|
||||
t.Fatalf("a disjoint range must be served in full, got:\n%s", r2.Content)
|
||||
}
|
||||
}
|
||||
|
||||
// full:true is the documented escape hatch: if the model has lost the earlier
|
||||
// content (compaction, handoff) it must still be able to force a re-read.
|
||||
func TestRead_FullBypassesSuppression(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
numberedFile(t, tmp, "f.txt", 50)
|
||||
|
||||
_, r2 := readTwice(t, tmp, `{"path":"f.txt"}`, `{"path":"f.txt","full":true}`)
|
||||
if !strings.Contains(r2.Content, "line 50") {
|
||||
t.Fatalf("full:true must bypass suppression, got:\n%s", r2.Content)
|
||||
}
|
||||
}
|
||||
|
||||
// The suppression notice has to tell the model how to force a re-read,
|
||||
// otherwise a model that has lost the content has no recovery path.
|
||||
func TestRead_SuppressionNoticeNamesTheEscapeHatch(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
numberedFile(t, tmp, "f.txt", 50)
|
||||
|
||||
_, r2 := readTwice(t, tmp, `{"path":"f.txt"}`, `{"path":"f.txt"}`)
|
||||
if !strings.Contains(r2.Content, "full") {
|
||||
t.Fatalf("notice must mention full:true as the escape hatch, got:\n%s", r2.Content)
|
||||
}
|
||||
}
|
||||
|
||||
// Suppression must not weaken the read-before-write guard.
|
||||
func TestRead_SuppressedReadStillCountsAsRead(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
numberedFile(t, tmp, "f.txt", 20)
|
||||
|
||||
rt := NewReadTracker()
|
||||
tool := NewReadTool(tmp, rt)
|
||||
for range 2 {
|
||||
if _, err := tool.Execute(context.Background(), json.RawMessage(`{"path":"f.txt"}`), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := rt.CheckRead(tmp, "f.txt"); err != nil {
|
||||
t.Fatalf("a suppressed re-read must still satisfy read-before-write: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,233 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func execRead(t *testing.T, cwd, params string) Result {
|
||||
t.Helper()
|
||||
tool := NewReadTool(cwd, nil)
|
||||
res, err := tool.Execute(context.Background(), json.RawMessage(params), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func TestReadTool_RawContentNoGutter(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
writeReadTestFile(t, tmp, "f.txt", "alpha\nbeta\ngamma\n")
|
||||
|
||||
res := execRead(t, tmp, `{"path": "f.txt"}`)
|
||||
if res.IsError {
|
||||
t.Fatalf("unexpected tool error: %s", res.Content)
|
||||
}
|
||||
if strings.Contains(res.Content, "│") {
|
||||
t.Fatalf("expected raw content without line-number gutter, got:\n%s", res.Content)
|
||||
}
|
||||
if !strings.HasPrefix(res.Content, "alpha\nbeta\ngamma") {
|
||||
t.Fatalf("unexpected content:\n%s", res.Content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadToolAcceptsFileAlias(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
writeReadTestFile(t, tmp, "f.txt", "alpha\nbeta\n")
|
||||
|
||||
res := execRead(t, tmp, `{"file":"f.txt"}`)
|
||||
if res.IsError || !strings.HasPrefix(res.Content, "alpha\nbeta") {
|
||||
t.Fatalf("file alias result = %#v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadToolDefaultsToBoundedOutput(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
lines := make([]string, DefaultReadLines+10)
|
||||
for i := range lines {
|
||||
lines[i] = fmt.Sprintf("line %d", i+1)
|
||||
}
|
||||
writeReadTestFile(t, tmp, "f.txt", strings.Join(lines, "\n"))
|
||||
|
||||
res := execRead(t, tmp, `{"path":"f.txt"}`)
|
||||
if res.IsError || !strings.Contains(res.Content, fmt.Sprintf("Use offset=%d to continue", DefaultReadLines+1)) {
|
||||
t.Fatalf("bounded read result = %s", res.Content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadTool_UserLimitContinuationNotice(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
var lines []string
|
||||
for i := 1; i <= 50; i++ {
|
||||
lines = append(lines, fmt.Sprintf("line %d", i))
|
||||
}
|
||||
writeReadTestFile(t, tmp, "f.txt", strings.Join(lines, "\n"))
|
||||
|
||||
res := execRead(t, tmp, `{"path": "f.txt", "offset": 10, "limit": 5}`)
|
||||
if res.IsError {
|
||||
t.Fatalf("unexpected tool error: %s", res.Content)
|
||||
}
|
||||
if !strings.HasPrefix(res.Content, "line 10") {
|
||||
t.Fatalf("expected content to start at line 10, got:\n%s", res.Content)
|
||||
}
|
||||
if !strings.Contains(res.Content, "Use offset=15 to continue") {
|
||||
t.Fatalf("expected continuation notice with offset=15, got:\n%s", res.Content)
|
||||
}
|
||||
if !strings.Contains(res.Content, "more lines in file") {
|
||||
t.Fatalf("expected remaining-lines notice, got:\n%s", res.Content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadTool_TruncationContinuationNotice(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
var lines []string
|
||||
for i := 1; i <= DefaultMaxLines+500; i++ {
|
||||
lines = append(lines, fmt.Sprintf("line %d", i))
|
||||
}
|
||||
writeReadTestFile(t, tmp, "f.txt", strings.Join(lines, "\n"))
|
||||
|
||||
res := execRead(t, tmp, `{"path": "f.txt", "full": true}`)
|
||||
if res.IsError {
|
||||
t.Fatalf("unexpected tool error: %s", res.Content)
|
||||
}
|
||||
notice := fmt.Sprintf("[showing lines 1-%d of %d. Use offset=%d to continue.]", DefaultMaxLines, DefaultMaxLines+500, DefaultMaxLines+1)
|
||||
if !strings.Contains(res.Content, notice) {
|
||||
t.Fatalf("expected notice %q, got tail:\n%s", notice, res.Content[len(res.Content)-200:])
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadTool_FirstLineExceedsByteLimit(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
writeReadTestFile(t, tmp, "big.min.js", strings.Repeat("x", DefaultMaxBytes+100))
|
||||
|
||||
res := execRead(t, tmp, `{"path": "big.min.js"}`)
|
||||
if res.IsError {
|
||||
t.Fatalf("unexpected tool error: %s", res.Content)
|
||||
}
|
||||
if !strings.Contains(res.Content, "Use shell: sed -n '1p'") {
|
||||
t.Fatalf("expected shell fallback hint, got:\n%s", res.Content)
|
||||
}
|
||||
}
|
||||
|
||||
func writeReadTestFile(t *testing.T, dir, name, content string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadTool_DirectoryReturnsListing(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
writeReadTestFile(t, tmp, "alpha.go", "package a\n")
|
||||
writeReadTestFile(t, tmp, "beta.go", "package b\n")
|
||||
if err := os.Mkdir(filepath.Join(tmp, "sub"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
res := execRead(t, tmp, `{"path": "."}`)
|
||||
if res.IsError {
|
||||
t.Fatalf("expected a listing, not an error: %s", res.Content)
|
||||
}
|
||||
for _, want := range []string{"alpha.go", "beta.go", "sub/"} {
|
||||
if !strings.Contains(res.Content, want) {
|
||||
t.Fatalf("listing missing %q, got:\n%s", want, res.Content)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(res.Content, "is a directory") {
|
||||
t.Fatalf("expected the listing to say the path is a directory, got:\n%s", res.Content)
|
||||
}
|
||||
}
|
||||
|
||||
// A directory must not satisfy the read-before-write check: marking it read
|
||||
// would let a later write to a same-named file bypass the guard.
|
||||
func TestReadTool_DirectoryDoesNotMarkRead(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
rt := NewReadTracker()
|
||||
tool := NewReadTool(tmp, rt)
|
||||
res, err := tool.Execute(context.Background(), json.RawMessage(`{"path": "."}`), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if res.IsError {
|
||||
t.Fatalf("unexpected tool error: %s", res.Content)
|
||||
}
|
||||
if err := rt.CheckRead(tmp, "."); err == nil {
|
||||
t.Fatal("reading a directory must not mark it as read")
|
||||
}
|
||||
}
|
||||
|
||||
// 5 reads in the analysed corpus failed on plausible-but-wrong paths, each
|
||||
// costing a round trip plus a follow-up find.
|
||||
func TestReadTool_NotFoundSuggestsNearestPaths(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(tmp, "internal", "ui", "theme"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeReadTestFile(t, filepath.Join(tmp, "internal", "ui", "theme"), "theme.go", "package theme\n")
|
||||
|
||||
res := execRead(t, tmp, `{"path":"internal/theme/theme.go"}`)
|
||||
if !res.IsError {
|
||||
t.Fatal("expected a not-found error")
|
||||
}
|
||||
if !strings.Contains(res.Content, filepath.Join("internal", "ui", "theme", "theme.go")) {
|
||||
t.Fatalf("expected the real path to be suggested, got:\n%s", res.Content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadTool_NotFoundWithNoCandidateStaysPlain(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
writeReadTestFile(t, tmp, "other.go", "package other\n")
|
||||
|
||||
res := execRead(t, tmp, `{"path":"internal/nothing/absent.go"}`)
|
||||
if !res.IsError {
|
||||
t.Fatal("expected a not-found error")
|
||||
}
|
||||
if strings.Contains(res.Content, "did you mean") {
|
||||
t.Fatalf("no candidate should mean no suggestion, got:\n%s", res.Content)
|
||||
}
|
||||
}
|
||||
|
||||
// The real-world miss was internal/theme/theme.go: the directory exists but
|
||||
// holds differently-named files, so a basename search finds nothing. Listing
|
||||
// the directory that does exist is the useful answer.
|
||||
func TestReadTool_NotFoundListsExistingParentDir(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(tmp, "internal", "theme"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeReadTestFile(t, filepath.Join(tmp, "internal", "theme"), "colors.go", "package theme\n")
|
||||
|
||||
res := execRead(t, tmp, `{"path":"internal/theme/theme.go"}`)
|
||||
if !res.IsError {
|
||||
t.Fatal("expected a not-found error")
|
||||
}
|
||||
if !strings.Contains(res.Content, "colors.go") {
|
||||
t.Fatalf("expected the existing directory to be listed, got:\n%s", res.Content)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReadToolHonoursDeadlineOnExpiredContext pins the DefaultToolTimeout
|
||||
// contract: when the caller's context is already expired, read must not
|
||||
// ignore that deadline and read the file anyway.
|
||||
func TestReadToolHonoursDeadlineOnExpiredContext(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
writeReadTestFile(t, tmp, "f.txt", "alpha\nbeta\n")
|
||||
|
||||
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
|
||||
defer cancel()
|
||||
|
||||
tool := NewReadTool(tmp, nil)
|
||||
res, err := tool.Execute(ctx, json.RawMessage(`{"path":"f.txt"}`), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !res.IsError {
|
||||
t.Fatalf("read on an expired context must not succeed; got content %q", res.Content)
|
||||
}
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
package builtin_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools/builtin"
|
||||
)
|
||||
|
||||
func dummyExecutor(_ context.Context, _ json.RawMessage, _ builtin.UIBridge) (builtin.Result, error) {
|
||||
return builtin.Result{Content: "ok"}, nil
|
||||
}
|
||||
|
||||
func TestRegistry_Register(t *testing.T) {
|
||||
r := builtin.NewRegistry()
|
||||
|
||||
tool := builtin.Tool{
|
||||
Schema: builtin.Schema{Name: "test", Description: "a test tool"},
|
||||
Execute: dummyExecutor,
|
||||
Source: "builtin",
|
||||
}
|
||||
|
||||
if err := r.Register(tool); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if r.Count() != 1 {
|
||||
t.Fatalf("expected 1 tool, got %d", r.Count())
|
||||
}
|
||||
|
||||
// Duplicate registration should fail.
|
||||
if err := r.Register(tool); err == nil {
|
||||
t.Fatal("expected error on duplicate registration")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistry_Replace(t *testing.T) {
|
||||
r := builtin.NewRegistry()
|
||||
|
||||
tool := builtin.Tool{
|
||||
Schema: builtin.Schema{Name: "test", Description: "v1"},
|
||||
Execute: dummyExecutor,
|
||||
Source: "builtin",
|
||||
}
|
||||
_ = r.Register(tool)
|
||||
|
||||
tool.Schema.Description = "v2"
|
||||
if err := r.Replace(tool); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
got, ok := r.Get("test")
|
||||
if !ok {
|
||||
t.Fatal("tool not found after replace")
|
||||
}
|
||||
if got.Schema.Description != "v2" {
|
||||
t.Fatalf("expected description v2, got %q", got.Schema.Description)
|
||||
}
|
||||
if r.Count() != 1 {
|
||||
t.Fatalf("replace should not duplicate; got count %d", r.Count())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistry_Unregister(t *testing.T) {
|
||||
r := builtin.NewRegistry()
|
||||
|
||||
_ = r.Register(builtin.Tool{
|
||||
Schema: builtin.Schema{Name: "a", Description: "tool a"},
|
||||
Execute: dummyExecutor,
|
||||
Source: "builtin",
|
||||
})
|
||||
_ = r.Register(builtin.Tool{
|
||||
Schema: builtin.Schema{Name: "b", Description: "tool b"},
|
||||
Execute: dummyExecutor,
|
||||
Source: "builtin",
|
||||
})
|
||||
|
||||
r.Unregister("a")
|
||||
|
||||
if r.Count() != 1 {
|
||||
t.Fatalf("expected 1 tool after unregister, got %d", r.Count())
|
||||
}
|
||||
if _, ok := r.Get("a"); ok {
|
||||
t.Fatal("tool 'a' should be gone")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistry_All_PreservesOrder(t *testing.T) {
|
||||
r := builtin.NewRegistry()
|
||||
|
||||
names := []string{"alpha", "beta", "gamma"}
|
||||
for _, name := range names {
|
||||
_ = r.Register(builtin.Tool{
|
||||
Schema: builtin.Schema{Name: name, Description: name},
|
||||
Execute: dummyExecutor,
|
||||
Source: "builtin",
|
||||
})
|
||||
}
|
||||
|
||||
all := r.All()
|
||||
if len(all) != 3 {
|
||||
t.Fatalf("expected 3 tools, got %d", len(all))
|
||||
}
|
||||
for i, tool := range all {
|
||||
if tool.Schema.Name != names[i] {
|
||||
t.Fatalf("order mismatch at %d: got %q, want %q", i, tool.Schema.Name, names[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistry_Schemas(t *testing.T) {
|
||||
r := builtin.NewRegistry()
|
||||
|
||||
_ = r.Register(builtin.Tool{
|
||||
Schema: builtin.Schema{
|
||||
Name: "read",
|
||||
Description: "Read a file",
|
||||
Parameters: json.RawMessage(`{"type":"object","properties":{"path":{"type":"string"}}}`),
|
||||
},
|
||||
Execute: dummyExecutor,
|
||||
Source: "builtin",
|
||||
})
|
||||
|
||||
schemas := r.Schemas()
|
||||
if len(schemas) != 1 {
|
||||
t.Fatalf("expected 1 schema, got %d", len(schemas))
|
||||
}
|
||||
if schemas[0].Name != "read" {
|
||||
t.Fatalf("expected schema name 'read', got %q", schemas[0].Name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistry_Validation(t *testing.T) {
|
||||
r := builtin.NewRegistry()
|
||||
|
||||
// Empty name.
|
||||
err := r.Register(builtin.Tool{
|
||||
Schema: builtin.Schema{Name: "", Description: "no name"},
|
||||
Execute: dummyExecutor,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for empty name")
|
||||
}
|
||||
|
||||
// Nil executor.
|
||||
err = r.Register(builtin.Tool{
|
||||
Schema: builtin.Schema{Name: "test", Description: "no exec"},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for nil executor")
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestShellReportsExitCodeRatherThanAGenericError covers the errorlint autofix
|
||||
// in 6d4e0be, which rewrote `err.(*exec.ExitError)` into errors.As here. The
|
||||
// same rewrite in grep.go dropped a companion exit-code check and turned failed
|
||||
// searches into empty results; this call site had no companion check to lose,
|
||||
// but nothing guarded the branch either. If the assertion ever stops matching,
|
||||
// a non-zero exit degrades to "error executing command" and the model loses the
|
||||
// exit code it uses to tell a failed command from a broken one.
|
||||
func TestShellReportsExitCodeRatherThanAGenericError(t *testing.T) {
|
||||
tool := NewShellTool(t.TempDir(), nil)
|
||||
|
||||
result, err := tool.Execute(context.Background(), json.RawMessage(`{"command":"exit 3"}`), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
if !result.IsError {
|
||||
t.Fatalf("a non-zero exit must be reported as an error, got %#v", result)
|
||||
}
|
||||
if result.ErrorKind != "command_exit" {
|
||||
t.Fatalf("error kind = %q, want command_exit; result: %#v", result.ErrorKind, result)
|
||||
}
|
||||
if !strings.Contains(result.Content, "[exit code: 3]") {
|
||||
t.Fatalf("exit code missing from result: %s", result.Content)
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const verboseGoTestOutput = `=== RUN TestAlpha
|
||||
--- PASS: TestAlpha (0.00s)
|
||||
=== RUN TestBeta
|
||||
beta_test.go:12: some chatty log line
|
||||
--- PASS: TestBeta (0.01s)
|
||||
PASS
|
||||
ok github.com/example/pkg 0.014s
|
||||
? github.com/example/pkg/empty [no test files]
|
||||
ok github.com/example/other (cached)
|
||||
`
|
||||
|
||||
func TestCollapseGoTest_KeepsOnlyPackageSummaries(t *testing.T) {
|
||||
got, collapsed := collapseGoTestOutput("go test ./... -v", verboseGoTestOutput, true)
|
||||
if !collapsed {
|
||||
t.Fatal("expected a passing go test run to be collapsed")
|
||||
}
|
||||
for _, want := range []string{
|
||||
"ok \tgithub.com/example/pkg\t0.014s",
|
||||
"? \tgithub.com/example/pkg/empty\t[no test files]",
|
||||
"ok \tgithub.com/example/other\t(cached)",
|
||||
} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("summary line missing: %q\ngot:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
for _, unwanted := range []string{"=== RUN", "--- PASS", "chatty log line"} {
|
||||
if strings.Contains(got, unwanted) {
|
||||
t.Errorf("per-test noise %q survived:\n%s", unwanted, got)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(got, "collapsed") {
|
||||
t.Errorf("expected a notice explaining the collapse, got:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A failing run is the case where the detail is the whole point.
|
||||
func TestCollapseGoTest_LeavesFailingRunsAlone(t *testing.T) {
|
||||
failing := verboseGoTestOutput + "--- FAIL: TestGamma (0.00s)\nFAIL\n"
|
||||
got, collapsed := collapseGoTestOutput("go test ./...", failing, false)
|
||||
if collapsed {
|
||||
t.Fatal("a failing run must not be collapsed")
|
||||
}
|
||||
if got != failing {
|
||||
t.Fatal("a failing run's output must be returned verbatim")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollapseGoTest_IgnoresOtherCommands(t *testing.T) {
|
||||
for _, cmd := range []string{"git status", "go build ./...", "gotestsum --format short"} {
|
||||
if _, collapsed := collapseGoTestOutput(cmd, verboseGoTestOutput, true); collapsed {
|
||||
t.Errorf("%q must not be treated as a go test invocation", cmd)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing to gain from collapsing output that is already just summaries, and
|
||||
// doing so would append a confusing notice.
|
||||
func TestCollapseGoTest_SkipsAlreadyTerseOutput(t *testing.T) {
|
||||
terse := "ok \tgithub.com/example/pkg\t0.014s\n"
|
||||
if _, collapsed := collapseGoTestOutput("go test ./...", terse, true); collapsed {
|
||||
t.Error("already-terse output should be left alone")
|
||||
}
|
||||
}
|
||||
|
||||
// Guard against collapsing a run that produced no recognisable summary at all,
|
||||
// which would leave the model with nothing.
|
||||
func TestCollapseGoTest_SkipsWhenNoSummaryLines(t *testing.T) {
|
||||
odd := "=== RUN TestAlpha\n--- PASS: TestAlpha (0.00s)\nPASS\n"
|
||||
if _, collapsed := collapseGoTestOutput("go test ./...", odd, true); collapsed {
|
||||
t.Error("output with no package summary lines should be left alone")
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestShellCancellationKillsGrandchildren is the guarantee /stop depends on.
|
||||
//
|
||||
// exec.CommandContext's default cancellation kills only the shell it
|
||||
// started. A shell's real work is a child of that shell, so without an
|
||||
// explicit process group the command survives its own cancellation: the
|
||||
// turn unwinds, the user is told it stopped, and `go test ./...` keeps
|
||||
// running. This drives the case directly -- a backgrounded grandchild that
|
||||
// outlives its parent shell -- and asserts it is gone.
|
||||
func TestShellCancellationKillsGrandchildren(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
pidFile := filepath.Join(dir, "child.pid")
|
||||
|
||||
// Background a long sleep, record its pid, then keep the parent shell
|
||||
// alive. Only a group-wide signal reaps the sleep.
|
||||
command := "sleep 300 & echo $! > " + pidFile + "; sleep 300"
|
||||
params, err := json.Marshal(ShellParams{Command: command, Timeout: 60})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
_, _ = makeShellExecutor(dir, nil)(ctx, params, NonInteractiveBridge{})
|
||||
}()
|
||||
|
||||
pid := waitForPID(t, pidFile)
|
||||
if !processAlive(pid) {
|
||||
t.Fatalf("grandchild %d was not running before cancellation", pid)
|
||||
}
|
||||
|
||||
cancel()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatal("the shell tool did not return after cancellation")
|
||||
}
|
||||
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if !processAlive(pid) {
|
||||
return
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
|
||||
// Do not leave a stray sleep behind if the assertion fails.
|
||||
_ = syscall.Kill(pid, syscall.SIGKILL)
|
||||
t.Fatalf("grandchild %d survived cancellation; /stop would not have stopped it", pid)
|
||||
}
|
||||
|
||||
// waitForPID blocks until the shell has recorded its background child's pid.
|
||||
func waitForPID(t *testing.T, path string) int {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(20 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err == nil {
|
||||
if pid, convErr := strconv.Atoi(strings.TrimSpace(string(raw))); convErr == nil && pid > 0 {
|
||||
return pid
|
||||
}
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("the shell never recorded a background child pid")
|
||||
return 0
|
||||
}
|
||||
|
||||
// processAlive reports whether pid still exists. Signal 0 performs the
|
||||
// permission and existence checks without delivering anything.
|
||||
func processAlive(pid int) bool {
|
||||
if syscall.Kill(pid, 0) != nil {
|
||||
return false
|
||||
}
|
||||
// A killed child can remain as a zombie when the test process is not
|
||||
// running under an init that reaps orphaned children. Zombies no longer
|
||||
// execute and therefore do not represent a surviving command.
|
||||
stat, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/stat")
|
||||
if err == nil {
|
||||
if closeParen := strings.LastIndex(string(stat), ")"); closeParen >= 0 && len(stat) > closeParen+2 {
|
||||
return stat[closeParen+2] != 'Z'
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
package builtin_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools/builtin"
|
||||
)
|
||||
|
||||
func TestTruncateHead_NoTruncation(t *testing.T) {
|
||||
content := "line1\nline2\nline3"
|
||||
result := builtin.TruncateHead(content, 100, 100000)
|
||||
|
||||
if result.Truncated {
|
||||
t.Fatal("should not be truncated")
|
||||
}
|
||||
if result.Content != content {
|
||||
t.Fatalf("content mismatch: got %q", result.Content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncateHead_ByLines(t *testing.T) {
|
||||
lines := make([]string, 100)
|
||||
for i := range lines {
|
||||
lines[i] = "x"
|
||||
}
|
||||
content := strings.Join(lines, "\n")
|
||||
|
||||
result := builtin.TruncateHead(content, 10, 100000)
|
||||
|
||||
if !result.Truncated {
|
||||
t.Fatal("should be truncated")
|
||||
}
|
||||
if result.OriginalLine != 100 {
|
||||
t.Fatalf("expected 100 original lines, got %d", result.OriginalLine)
|
||||
}
|
||||
if !strings.Contains(result.Content, "[truncated:") {
|
||||
t.Fatal("should contain truncation notice")
|
||||
}
|
||||
if !strings.Contains(result.Content, "10/100 lines") {
|
||||
t.Fatalf("truncation notice should mention line counts, got: %s", result.Content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncateHead_ByBytes(t *testing.T) {
|
||||
content := strings.Repeat("a", 1000)
|
||||
|
||||
result := builtin.TruncateHead(content, 10000, 100)
|
||||
|
||||
if !result.Truncated {
|
||||
t.Fatal("should be truncated by bytes")
|
||||
}
|
||||
if result.OriginalSize != 1000 {
|
||||
t.Fatalf("expected 1000 original bytes, got %d", result.OriginalSize)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncateTail_NoTruncation(t *testing.T) {
|
||||
content := "line1\nline2\nline3"
|
||||
result := builtin.TruncateTail(content, 100, 100000)
|
||||
|
||||
if result.Truncated {
|
||||
t.Fatal("should not be truncated")
|
||||
}
|
||||
if result.Content != content {
|
||||
t.Fatalf("content mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncateTail_ByLines(t *testing.T) {
|
||||
lines := make([]string, 100)
|
||||
for i := range lines {
|
||||
lines[i] = "x"
|
||||
}
|
||||
content := strings.Join(lines, "\n")
|
||||
|
||||
result := builtin.TruncateTail(content, 10, 100000)
|
||||
|
||||
if !result.Truncated {
|
||||
t.Fatal("should be truncated")
|
||||
}
|
||||
if !strings.Contains(result.Content, "last 10/100 lines") {
|
||||
t.Fatalf("truncation notice should mention line counts, got: %s", result.Content)
|
||||
}
|
||||
// The kept content should be the last 10 lines (all "x").
|
||||
kept := strings.Split(strings.TrimSpace(result.Content), "\n")
|
||||
// Last 10 lines + truncation notice line + blank line = 12.
|
||||
if len(kept) < 10 {
|
||||
t.Fatalf("expected at least 10 kept lines, got %d", len(kept))
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatSize(t *testing.T) {
|
||||
cases := []struct {
|
||||
input int
|
||||
expected string
|
||||
}{
|
||||
{500, "500B"},
|
||||
{1024, "1.0KB"},
|
||||
{51200, "50.0KB"},
|
||||
{1048576, "1.0MB"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got := builtin.FormatSize(tc.input)
|
||||
if got != tc.expected {
|
||||
t.Errorf("FormatSize(%d) = %q, want %q", tc.input, got, tc.expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestWriteTool_PopulatesDiffDetails_NewFile(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
path := filepath.Join(tmp, "f.txt")
|
||||
|
||||
tool := NewWriteTool(tmp, NewMutationQueue(), nil)
|
||||
params := `{"path": "f.txt", "content": "hello\n"}`
|
||||
res, err := tool.Execute(context.Background(), json.RawMessage(params), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if res.IsError {
|
||||
t.Fatalf("unexpected tool error: %s", res.Content)
|
||||
}
|
||||
|
||||
details, ok := res.Details.(DiffDetails)
|
||||
if !ok {
|
||||
t.Fatalf("expected Details to be a DiffDetails, got %T", res.Details)
|
||||
}
|
||||
if details.OldContent != "" {
|
||||
t.Fatalf("expected empty OldContent for a new file, got %q", details.OldContent)
|
||||
}
|
||||
if details.NewContent != "hello\n" {
|
||||
t.Fatalf("NewContent mismatch: got %q", details.NewContent)
|
||||
}
|
||||
if details.Path != path {
|
||||
t.Fatalf("Path mismatch: got %q want %q", details.Path, path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteTool_PopulatesDiffDetails_Overwrite(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
path := filepath.Join(tmp, "f.txt")
|
||||
original := "old content\n"
|
||||
if err := os.WriteFile(path, []byte(original), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tool := NewWriteTool(tmp, NewMutationQueue(), nil)
|
||||
params := `{"path": "f.txt", "content": "new content\n", "overwrite": true}`
|
||||
res, err := tool.Execute(context.Background(), json.RawMessage(params), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if res.IsError {
|
||||
t.Fatalf("unexpected tool error: %s", res.Content)
|
||||
}
|
||||
|
||||
details, ok := res.Details.(DiffDetails)
|
||||
if !ok {
|
||||
t.Fatalf("expected Details to be a DiffDetails, got %T", res.Details)
|
||||
}
|
||||
if details.OldContent != original {
|
||||
t.Fatalf("OldContent mismatch: got %q want %q", details.OldContent, original)
|
||||
}
|
||||
if details.NewContent != "new content\n" {
|
||||
t.Fatalf("NewContent mismatch: got %q", details.NewContent)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWriteTool_RespectsParentContextDeadline is the regression test for
|
||||
// tau-6wa: the executor used to create a timeout-derived context and then
|
||||
// discard it, passing the original (unbounded) ctx to every downstream I/O
|
||||
// call. With that bug, an already-expired parent context would have no
|
||||
// effect on the write. Here the parent's deadline has already passed when
|
||||
// Execute is called, so the executor must surface a timeout error instead
|
||||
// of proceeding to write the file.
|
||||
func TestWriteTool_RespectsParentContextDeadline(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
path := filepath.Join(tmp, "f.txt")
|
||||
|
||||
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
|
||||
defer cancel()
|
||||
|
||||
tool := NewWriteTool(tmp, NewMutationQueue(), nil)
|
||||
params := `{"path": "f.txt", "content": "hello\n"}`
|
||||
res, err := tool.Execute(ctx, json.RawMessage(params), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !res.IsError {
|
||||
t.Fatalf("expected a timeout error result for an already-expired context, got success: %+v", res)
|
||||
}
|
||||
|
||||
if _, statErr := os.Stat(path); statErr == nil {
|
||||
t.Fatal("expected no file to be written when the context had already expired")
|
||||
}
|
||||
}
|
||||
|
||||
// TestMutationToolsLeaveNoUnrestorableCheckpoints guards the decision that the
|
||||
// workspace mutation tools carry no rollback state. A pre-mutation checkpoint
|
||||
// writer whose only reader (CheckpointStore.RestoreLatest) has no production
|
||||
// caller, and whose store is never pruned, is dead weight and grows the
|
||||
// workspace without bound. If the inert writer is reintroduced without a
|
||||
// reachable restore caller, this fails.
|
||||
func TestMutationToolsLeaveNoUnrestorableCheckpoints(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(tmp, "f.txt"), []byte("hello\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
write := NewWriteTool(tmp, NewMutationQueue(), nil)
|
||||
if res, err := write.Execute(context.Background(), json.RawMessage(`{"path":"g.txt","content":"new\n"}`), nil); err != nil || res.IsError {
|
||||
t.Fatalf("write: err=%v res=%+v", err, res)
|
||||
}
|
||||
|
||||
edit := NewEditTool(tmp, NewMutationQueue(), nil)
|
||||
if res, err := edit.Execute(context.Background(), json.RawMessage(`{"path":"f.txt","edits":[{"old_text":"hello","new_text":"hi"}]}`), nil); err != nil || res.IsError {
|
||||
t.Fatalf("edit: err=%v res=%+v", err, res)
|
||||
}
|
||||
|
||||
store := filepath.Join(tmp, ".git", "archie-checkpoints")
|
||||
if _, err := os.Stat(store); !os.IsNotExist(err) {
|
||||
t.Fatalf("mutating tools left unrestorable checkpoint data at %s: stat err = %v", store, err)
|
||||
}
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestToolClassificationIsIdempotent(t *testing.T) {
|
||||
t.Run("zero value is not idempotent", func(t *testing.T) {
|
||||
var c ToolClassification
|
||||
if c.IsIdempotent() {
|
||||
t.Error("zero classification should not be idempotent")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("explicit idempotent flag", func(t *testing.T) {
|
||||
if !ClassIdempotent.IsIdempotent() {
|
||||
t.Error("ClassIdempotent should be idempotent")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("idempotent is not mutating", func(t *testing.T) {
|
||||
if ClassIdempotent.IsMutating() {
|
||||
t.Error("idempotent should not be mutating")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestToolClassificationIsMutating(t *testing.T) {
|
||||
t.Run("zero value is not mutating", func(t *testing.T) {
|
||||
var c ToolClassification
|
||||
if c.IsMutating() {
|
||||
t.Error("zero classification should not be mutating")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("explicit mutating flag", func(t *testing.T) {
|
||||
if !ClassMutating.IsMutating() {
|
||||
t.Error("ClassMutating should be mutating")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("mutating is not idempotent", func(t *testing.T) {
|
||||
if ClassMutating.IsIdempotent() {
|
||||
t.Error("mutating should not be idempotent")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestToolClassificationCombined(t *testing.T) {
|
||||
c := ClassIdempotent | ClassMutating
|
||||
if !c.IsIdempotent() {
|
||||
t.Error("combined should be idempotent")
|
||||
}
|
||||
if !c.IsMutating() {
|
||||
t.Error("combined should be mutating")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolClassificationIsApprovalRequired(t *testing.T) {
|
||||
t.Run("zero value does not require approval", func(t *testing.T) {
|
||||
var c ToolClassification
|
||||
if c.IsApprovalRequired() {
|
||||
t.Error("zero classification should not require approval")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("explicit approval flag", func(t *testing.T) {
|
||||
if !RequiresApproval.IsApprovalRequired() {
|
||||
t.Error("RequiresApproval should require approval")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("approval is independent of idempotent", func(t *testing.T) {
|
||||
c := ClassIdempotent | RequiresApproval
|
||||
if !c.IsApprovalRequired() {
|
||||
t.Error("idempotent + approval should require approval")
|
||||
}
|
||||
if !c.IsIdempotent() {
|
||||
t.Error("idempotent + approval should still be idempotent")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("approval is independent of mutating", func(t *testing.T) {
|
||||
c := ClassMutating | RequiresApproval
|
||||
if !c.IsApprovalRequired() {
|
||||
t.Error("mutating + approval should require approval")
|
||||
}
|
||||
if !c.IsMutating() {
|
||||
t.Error("mutating + approval should still be mutating")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestToolClassificationString(t *testing.T) {
|
||||
tests := []struct {
|
||||
c ToolClassification
|
||||
want string
|
||||
}{
|
||||
{0, "default"},
|
||||
{ClassIdempotent, "idempotent"},
|
||||
{ClassMutating, "mutating"},
|
||||
{ClassIdempotent | ClassMutating, "idempotent|mutating"},
|
||||
{RequiresApproval, "requires_approval"},
|
||||
{ClassMutating | RequiresApproval, "mutating|requires_approval"},
|
||||
{ToolClassification(8), "unknown"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := tt.c.String()
|
||||
if got != tt.want {
|
||||
t.Errorf("String() = %q, want %q", got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassificationJSONRoundTrip(t *testing.T) {
|
||||
e := ToolEntry{
|
||||
Name: "classified",
|
||||
Toolset: "test",
|
||||
Description: "A classified tool",
|
||||
Handler: noopHandler,
|
||||
Classification: ClassIdempotent,
|
||||
}
|
||||
|
||||
data, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
|
||||
var decoded ToolEntry
|
||||
if err := json.Unmarshal(data, &decoded); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
|
||||
if decoded.Classification != ClassIdempotent {
|
||||
t.Errorf("Classification = %v after round-trip, want idempotent", decoded.Classification)
|
||||
}
|
||||
}
|
||||
@@ -1,200 +0,0 @@
|
||||
package command_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools/command"
|
||||
)
|
||||
|
||||
// TestHardlineBlocks covers the commands that must never run.
|
||||
func TestHardlineBlocks(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
line string
|
||||
rule string
|
||||
}{
|
||||
{"root delete", "rm -rf /", "recursive-root-delete"},
|
||||
{"root delete glob", "rm -rf /*", "recursive-root-delete"},
|
||||
{"root delete dot", "rm -rf /.", "recursive-root-delete"},
|
||||
{"root delete long flag", "rm --recursive --force /", "recursive-root-delete"},
|
||||
{"root delete bundled reverse", "rm -fr /", "recursive-root-delete"},
|
||||
// An absolute path must be judged the same as a bare name: every sibling
|
||||
// rule already normalises through baseName, and baseName's own doc says
|
||||
// /sbin/reboot and reboot are meant to be judged alike. Comparing the raw
|
||||
// segment name here let /bin/rm -rf / through while blocking rm -rf /.
|
||||
{"absolute path root delete", "/bin/rm -rf /", "recursive-root-delete"},
|
||||
{"absolute path root delete reverse", "/usr/bin/rm -fr /", "recursive-root-delete"},
|
||||
{"absolute path root delete long flag", "/usr/bin/rm --recursive --force /", "recursive-root-delete"},
|
||||
{"absolute path etc delete", "/bin/rm -rf /etc", "recursive-root-delete"},
|
||||
{"absolute path sudo delete", "sudo /bin/rm -rf /", "recursive-root-delete"},
|
||||
{"home delete", "rm -rf ~", "recursive-root-delete"},
|
||||
{"home var delete", "rm -rf $HOME", "recursive-root-delete"},
|
||||
{"home brace delete", "rm -rf ${HOME}/", "recursive-root-delete"},
|
||||
{"etc delete", "rm -rf /etc", "recursive-root-delete"},
|
||||
{"usr glob delete", "rm -rf /usr/*", "recursive-root-delete"},
|
||||
{"quoted root delete", `rm -rf "/"`, "recursive-root-delete"},
|
||||
{"env prefixed delete", "FOO=bar rm -rf /", "recursive-root-delete"},
|
||||
{"sudo delete", "sudo rm -rf /", "recursive-root-delete"},
|
||||
|
||||
{"mkfs", "mkfs.ext4 /dev/sda1", "filesystem-format"},
|
||||
{"bare mkfs", "mkfs /dev/sdb", "filesystem-format"},
|
||||
|
||||
{"dd to disk", "dd if=/dev/zero of=/dev/sda bs=1M", "block-device-write"},
|
||||
{"dd to nvme", "dd if=x.img of=/dev/nvme0n1", "block-device-write"},
|
||||
{"redirect to disk", "echo x > /dev/sda", "block-device-write"},
|
||||
|
||||
{"fork bomb", ":(){ :|:& };:", "fork-bomb"},
|
||||
{"fork bomb compact", ":(){:|:&};:", "fork-bomb"},
|
||||
|
||||
{"kill all", "kill -9 -1", "kill-all-processes"},
|
||||
|
||||
{"shutdown", "shutdown -h now", "system-power"},
|
||||
{"reboot", "reboot", "system-power"},
|
||||
{"poweroff path", "/sbin/poweroff", "system-power"},
|
||||
{"init 0", "init 0", "system-power"},
|
||||
{"telinit 6", "telinit 6", "system-power"},
|
||||
{"systemctl reboot", "systemctl reboot", "system-power"},
|
||||
|
||||
{"sudo stdin", "sudo -S ls", "sudo-stdin-password"},
|
||||
|
||||
{"pkill daemon", "pkill archied", "daemon-self-termination"},
|
||||
{"killall daemon", "killall -9 archied", "daemon-self-termination"},
|
||||
{"systemctl stop daemon", "systemctl stop archied", "daemon-self-termination"},
|
||||
{"docker stop daemon", "docker stop archie-core-archied-1", "daemon-self-termination"},
|
||||
{"docker rm daemon", "docker rm -f archie-core-archied-1", "daemon-self-termination"},
|
||||
|
||||
{"launch daemon", "archied -config /etc/archie/config.toml", "daemon-launch"},
|
||||
{"nohup daemon", "nohup archied &", "daemon-launch"},
|
||||
|
||||
{"hidden after separator", "echo hello; rm -rf /", "recursive-root-delete"},
|
||||
{"hidden after and", "cd /tmp && rm -rf /", "recursive-root-delete"},
|
||||
{"hidden after pipe", "cat x | rm -rf /", "recursive-root-delete"},
|
||||
{"hidden in substitution", "echo $(rm -rf /)", "recursive-root-delete"},
|
||||
{"hidden in backticks", "echo `rm -rf /`", "recursive-root-delete"},
|
||||
{"hidden in subshell", "(rm -rf /)", "recursive-root-delete"},
|
||||
{"hidden after newline", "echo hi\nrm -rf /", "recursive-root-delete"},
|
||||
|
||||
// Wrapped forms. These are not exotic: `bash -c` is a shape
|
||||
// models produce unprompted, and without unwrapping every rule
|
||||
// above is one quotation mark away from being bypassed.
|
||||
{"bash -c", `bash -c "rm -rf /"`, "recursive-root-delete"},
|
||||
{"sh -c single quoted", `sh -c 'rm -rf /'`, "recursive-root-delete"},
|
||||
{"eval", `eval "rm -rf /"`, "recursive-root-delete"},
|
||||
{"nested shells", `bash -c "sh -c 'rm -rf /'"`, "recursive-root-delete"},
|
||||
{"xargs", "xargs rm -rf /", "recursive-root-delete"},
|
||||
{"timeout with duration", "timeout 30 rm -rf /", "recursive-root-delete"},
|
||||
{"nice with flag value", "nice -n 10 rm -rf /", "recursive-root-delete"},
|
||||
{"env assignment", "env FOO=bar rm -rf /", "recursive-root-delete"},
|
||||
{"nohup wrapping delete", "nohup rm -rf / &", "recursive-root-delete"},
|
||||
{"wrapped power command", `bash -c "reboot"`, "system-power"},
|
||||
{"wrapped daemon kill", `sh -c "pkill archied"`, "daemon-self-termination"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
err := command.Hardline(tc.line)
|
||||
if err == nil {
|
||||
t.Fatalf("Hardline(%q) allowed the command", tc.line)
|
||||
}
|
||||
var blocked *command.Blocked
|
||||
if !errors.As(err, &blocked) {
|
||||
t.Fatalf("error type = %T, want *command.Blocked", err)
|
||||
}
|
||||
if blocked.Rule != tc.rule {
|
||||
t.Errorf("rule = %q, want %q (reason: %s)", blocked.Rule, tc.rule, blocked.Reason)
|
||||
}
|
||||
if blocked.Reason == "" {
|
||||
t.Error("refusal carries no reason, so the model cannot tell why")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestHardlineAllows is the half that decides whether this is usable. A
|
||||
// blocklist that fires on commit messages and ordinary work would be
|
||||
// turned off within a day, so the quoting and command-position analysis
|
||||
// matters as much as the patterns.
|
||||
func TestHardlineAllows(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
line string
|
||||
}{
|
||||
{"echoing the string", `echo "rm -rf /"`},
|
||||
{"commit message", `git commit -m "revert the rm -rf / change"`},
|
||||
{"commit message single quotes", `git commit -m 'stop using rm -rf / in scripts'`},
|
||||
{"pr title", `gh pr create --title "guard against rm -rf /"`},
|
||||
{"grep for the pattern", `grep -r "rm -rf /" .`},
|
||||
{"writing a doc that mentions reboot", `echo "reboot the machine" > notes.txt`},
|
||||
|
||||
{"ordinary recursive delete", "rm -rf ./build"},
|
||||
{"recursive delete in workspace", "rm -rf /workspace/tmp"},
|
||||
{"recursive delete of subdir", "rm -rf /var/lib/archie/work/tmp"},
|
||||
{"non-recursive root file", "rm /tmp/x"},
|
||||
// Normalising through baseName must not turn an ordinary recursive delete
|
||||
// that happens to use an absolute path into a refusal.
|
||||
{"absolute path recursive delete in workspace", "/bin/rm -rf /workspace/tmp"},
|
||||
|
||||
{"dd to a file", "dd if=/dev/zero of=disk.img bs=1M count=10"},
|
||||
{"redirect to null", "echo x > /dev/null"},
|
||||
{"redirect to a file", "go test ./... > out.txt"},
|
||||
|
||||
{"killing a pid", "kill -9 12345"},
|
||||
{"pkill something else", "pkill node"},
|
||||
{"systemctl status", "systemctl status archied"},
|
||||
{"systemctl restart something else", "systemctl restart nginx"},
|
||||
{"docker ps", "docker ps -a"},
|
||||
{"docker stop another container", "docker stop nats"},
|
||||
|
||||
{"sudo without stdin", "sudo apt-get update"},
|
||||
{"ordinary build", "go build ./..."},
|
||||
{"chained ordinary commands", "cd /workspace && go test ./... && git status"},
|
||||
{"empty", ""},
|
||||
{"whitespace", " "},
|
||||
|
||||
// The unwrapping must not turn ordinary wrapped commands into
|
||||
// refusals.
|
||||
{"bash -c ordinary", `bash -c "go test ./..."`},
|
||||
{"bash -c mentioning the string", `bash -c 'echo "rm -rf /"'`},
|
||||
{"xargs ordinary", "find . -name '*.tmp' | xargs rm -f"},
|
||||
{"timeout ordinary", "timeout 30 go test ./..."},
|
||||
{"env ordinary", "env GOFLAGS=-mod=mod go build ./..."},
|
||||
{"nohup ordinary", "nohup ./long-running-job &"},
|
||||
{"deeply nested ordinary", `bash -c "sh -c 'echo hello'"`},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if err := command.Hardline(tc.line); err != nil {
|
||||
t.Errorf("Hardline(%q) blocked an ordinary command: %v", tc.line, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBlockedErrorNamesTheSegment keeps the refusal actionable: the model
|
||||
// has to be able to tell which part of a chained command was objected to.
|
||||
func TestBlockedErrorNamesTheSegment(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
err := command.Hardline("go build ./... && rm -rf /etc")
|
||||
if err == nil {
|
||||
t.Fatal("Hardline allowed a recursive delete of /etc")
|
||||
}
|
||||
msg := err.Error()
|
||||
if !strings.Contains(msg, "rm -rf /etc") {
|
||||
t.Errorf("error %q does not name the offending segment", msg)
|
||||
}
|
||||
if strings.Contains(msg, "go build") {
|
||||
t.Errorf("error %q blames the wrong segment", msg)
|
||||
}
|
||||
}
|
||||
@@ -1,511 +0,0 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIsBridgeTool(t *testing.T) {
|
||||
if !IsBridgeTool(BridgeToolSearch) {
|
||||
t.Error("tool_search should be a bridge tool")
|
||||
}
|
||||
if !IsBridgeTool(BridgeToolDescribe) {
|
||||
t.Error("tool_describe should be a bridge tool")
|
||||
}
|
||||
if !IsBridgeTool(BridgeToolCall) {
|
||||
t.Error("tool_call should be a bridge tool")
|
||||
}
|
||||
if IsBridgeTool("ordinary_tool") {
|
||||
t.Error("ordinary_tool should not be a bridge tool")
|
||||
}
|
||||
if IsBridgeTool("") {
|
||||
t.Error("empty string should not be a bridge tool")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBridgeTools(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
bt := BridgeTools(r)
|
||||
|
||||
if len(bt) != 3 {
|
||||
t.Fatalf("expected 3 bridge tools, got %d", len(bt))
|
||||
}
|
||||
|
||||
names := make(map[string]bool)
|
||||
for _, e := range bt {
|
||||
names[e.Name] = true
|
||||
if e.Handler == nil {
|
||||
t.Errorf("bridge tool %q has nil handler", e.Name)
|
||||
}
|
||||
if !e.Classification.IsIdempotent() {
|
||||
t.Errorf("bridge tool %q should be idempotent", e.Name)
|
||||
}
|
||||
if e.Toolset != "bridge" {
|
||||
t.Errorf("bridge tool %q has toolset %q, want 'bridge'", e.Name, e.Toolset)
|
||||
}
|
||||
}
|
||||
|
||||
if !names[BridgeToolSearch] {
|
||||
t.Error("missing tool_search")
|
||||
}
|
||||
if !names[BridgeToolDescribe] {
|
||||
t.Error("missing tool_describe")
|
||||
}
|
||||
if !names[BridgeToolCall] {
|
||||
t.Error("missing tool_call")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBridgeToolSearch(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
|
||||
_ = r.Register(ToolEntry{
|
||||
Name: "read_file",
|
||||
Toolset: "file",
|
||||
Description: "Read a file from disk",
|
||||
Handler: noopHandler,
|
||||
})
|
||||
_ = r.Register(ToolEntry{
|
||||
Name: "write_file",
|
||||
Toolset: "file",
|
||||
Description: "Write content to a file",
|
||||
Handler: noopHandler,
|
||||
})
|
||||
_ = r.Register(ToolEntry{
|
||||
Name: "git_commit",
|
||||
Toolset: "git",
|
||||
Description: "Create a git commit",
|
||||
Handler: noopHandler,
|
||||
})
|
||||
|
||||
bt := BridgeTools(r)
|
||||
var searchTool ToolEntry
|
||||
for _, e := range bt {
|
||||
if e.Name == BridgeToolSearch {
|
||||
searchTool = e
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("search all", func(t *testing.T) {
|
||||
out, err := searchTool.Handler(context.Background(), map[string]any{"keyword": ""})
|
||||
if err != nil {
|
||||
t.Fatalf("tool_search error: %v", err)
|
||||
}
|
||||
result, ok := out.(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("out is %T, want map[string]any", out)
|
||||
}
|
||||
tools, ok := result["tools"].([]ToolSummary)
|
||||
if !ok {
|
||||
t.Fatalf("result[\"tools\"] is %T, want []ToolSummary", result["tools"])
|
||||
}
|
||||
if len(tools) != 3 {
|
||||
t.Errorf("expected 3 tools, got %d", len(tools))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("search by keyword", func(t *testing.T) {
|
||||
out, err := searchTool.Handler(context.Background(), map[string]any{"keyword": "file"})
|
||||
if err != nil {
|
||||
t.Fatalf("tool_search error: %v", err)
|
||||
}
|
||||
result, ok := out.(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("out is %T, want map[string]any", out)
|
||||
}
|
||||
tools, ok := result["tools"].([]ToolSummary)
|
||||
if !ok {
|
||||
t.Fatalf("result[\"tools\"] is %T, want []ToolSummary", result["tools"])
|
||||
}
|
||||
if len(tools) != 2 {
|
||||
t.Errorf("expected 2 file tools, got %d", len(tools))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("search no match", func(t *testing.T) {
|
||||
out, err := searchTool.Handler(context.Background(), map[string]any{"keyword": "nonexistent"})
|
||||
if err != nil {
|
||||
t.Fatalf("tool_search error: %v", err)
|
||||
}
|
||||
result, ok := out.(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("out is %T, want map[string]any", out)
|
||||
}
|
||||
tools, ok := result["tools"].([]ToolSummary)
|
||||
if !ok {
|
||||
t.Fatalf("result[\"tools\"] is %T, want []ToolSummary", result["tools"])
|
||||
}
|
||||
if len(tools) != 0 {
|
||||
t.Errorf("expected 0 tools, got %d", len(tools))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("bridge tools excluded from results", func(t *testing.T) {
|
||||
out, err := searchTool.Handler(context.Background(), map[string]any{"keyword": "tool_"})
|
||||
if err != nil {
|
||||
t.Fatalf("tool_search error: %v", err)
|
||||
}
|
||||
result, ok := out.(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("out is %T, want map[string]any", out)
|
||||
}
|
||||
tools, ok := result["tools"].([]ToolSummary)
|
||||
if !ok {
|
||||
t.Fatalf("result[\"tools\"] is %T, want []ToolSummary", result["tools"])
|
||||
}
|
||||
for _, ts := range tools {
|
||||
if IsBridgeTool(ts.Name) {
|
||||
t.Errorf("bridge tool %q should not appear in search results", ts.Name)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestBridgeToolDescribe(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
_ = r.Register(ToolEntry{
|
||||
Name: "read_file",
|
||||
Toolset: "file",
|
||||
Description: "Read a file from disk",
|
||||
Handler: noopHandler,
|
||||
Schema: JSONSchema{
|
||||
"type": "object",
|
||||
"properties": JSONSchema{
|
||||
"path": JSONSchema{"type": "string"},
|
||||
},
|
||||
},
|
||||
RequiresEnv: []string{"HOME"},
|
||||
})
|
||||
|
||||
bt := BridgeTools(r)
|
||||
var describeTool ToolEntry
|
||||
for _, e := range bt {
|
||||
if e.Name == BridgeToolDescribe {
|
||||
describeTool = e
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("describe existing tool", func(t *testing.T) {
|
||||
out, err := describeTool.Handler(context.Background(), map[string]any{"name": "read_file"})
|
||||
if err != nil {
|
||||
t.Fatalf("tool_describe error: %v", err)
|
||||
}
|
||||
result, ok := out.(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("out is %T, want map[string]any", out)
|
||||
}
|
||||
toolMap, ok := result["tool"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("result[\"tool\"] is %T, want map[string]any", result["tool"])
|
||||
}
|
||||
if toolMap["name"] != "read_file" {
|
||||
t.Errorf("name = %v, want 'read_file'", toolMap["name"])
|
||||
}
|
||||
if toolMap["description"] != "Read a file from disk" {
|
||||
t.Errorf("description = %v", toolMap["description"])
|
||||
}
|
||||
if toolMap["toolset"] != "file" {
|
||||
t.Errorf("toolset = %v, want 'file'", toolMap["toolset"])
|
||||
}
|
||||
if toolMap["schema"] == nil {
|
||||
t.Error("schema should not be nil")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("describe missing tool", func(t *testing.T) {
|
||||
_, err := describeTool.Handler(context.Background(), map[string]any{"name": "nope"})
|
||||
if err == nil {
|
||||
t.Error("expected error for missing tool")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("describe without name", func(t *testing.T) {
|
||||
_, err := describeTool.Handler(context.Background(), map[string]any{})
|
||||
if err == nil {
|
||||
t.Error("expected error for missing name parameter")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestBridgeToolCall(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
_ = r.Register(ToolEntry{
|
||||
Name: "echo",
|
||||
Handler: echoHandler,
|
||||
})
|
||||
|
||||
bt := BridgeTools(r)
|
||||
var callTool ToolEntry
|
||||
for _, e := range bt {
|
||||
if e.Name == BridgeToolCall {
|
||||
callTool = e
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("call existing tool", func(t *testing.T) {
|
||||
out, err := callTool.Handler(context.Background(), map[string]any{
|
||||
"name": "echo",
|
||||
"input": map[string]any{"msg": "hello"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("tool_call error: %v", err)
|
||||
}
|
||||
m, ok := out.(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("out is %T, want map[string]any", out)
|
||||
}
|
||||
if m["msg"] != "hello" {
|
||||
t.Errorf("msg = %v, want 'hello'", m["msg"])
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("call missing tool", func(t *testing.T) {
|
||||
_, err := callTool.Handler(context.Background(), map[string]any{"name": "nope"})
|
||||
if err == nil {
|
||||
t.Error("expected error for missing tool")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("call without name", func(t *testing.T) {
|
||||
_, err := callTool.Handler(context.Background(), map[string]any{})
|
||||
if err == nil {
|
||||
t.Error("expected error for missing name")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("cannot call bridge tool recursively", func(t *testing.T) {
|
||||
_, err := callTool.Handler(context.Background(), map[string]any{"name": BridgeToolSearch})
|
||||
if err == nil {
|
||||
t.Error("expected error when calling bridge tool")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestBridgeToolsRegistration(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
for _, e := range BridgeTools(r) {
|
||||
if err := r.Register(e); err != nil {
|
||||
t.Fatalf("register bridge tool %q: %v", e.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
available := r.Available()
|
||||
if len(available) != 3 {
|
||||
t.Errorf("expected 3 bridge tools registered, got %d", len(available))
|
||||
}
|
||||
}
|
||||
|
||||
func TestComposeForTurnMergesBaseExtrasAndBridge(t *testing.T) {
|
||||
base := NewRegistry()
|
||||
_ = base.Register(ToolEntry{Name: "memory_search", Toolset: "memory", Handler: noopHandler, Description: "Search memory"})
|
||||
extra := []ToolEntry{
|
||||
{Name: "session_resume", Toolset: "session", Handler: noopHandler, Description: "Resume a session"},
|
||||
}
|
||||
|
||||
composed, err := ComposeForTurn(base, extra)
|
||||
if err != nil {
|
||||
t.Fatalf("ComposeForTurn: %v", err)
|
||||
}
|
||||
|
||||
names := make(map[string]bool)
|
||||
for _, e := range composed.All() {
|
||||
names[e.Name] = true
|
||||
}
|
||||
|
||||
if !names["memory_search"] {
|
||||
t.Error("composed registry missing base tool memory_search")
|
||||
}
|
||||
if !names["session_resume"] {
|
||||
t.Error("composed registry missing extra tool session_resume")
|
||||
}
|
||||
for _, bridge := range []string{BridgeToolSearch, BridgeToolDescribe, BridgeToolCall} {
|
||||
if !names[bridge] {
|
||||
t.Errorf("composed registry missing bridge tool %q", bridge)
|
||||
}
|
||||
}
|
||||
|
||||
// The bridge handlers must be wired to the composed registry so they can
|
||||
// discover both base and extra tools.
|
||||
if _, ok := composed.Get(BridgeToolSearch); !ok {
|
||||
t.Errorf("bridge tool %q not present in composed registry", BridgeToolSearch)
|
||||
}
|
||||
}
|
||||
|
||||
func TestComposeForTurnDoesNotMutateBaseRegistry(t *testing.T) {
|
||||
base := NewRegistry()
|
||||
_ = base.Register(ToolEntry{Name: "memory_search", Handler: noopHandler, Description: "Search memory"})
|
||||
|
||||
if _, err := ComposeForTurn(base, nil); err != nil {
|
||||
t.Fatalf("ComposeForTurn: %v", err)
|
||||
}
|
||||
|
||||
if _, ok := base.Get(BridgeToolSearch); ok {
|
||||
t.Error("ComposeForTurn must not register bridge tools into the base registry")
|
||||
}
|
||||
if got := len(base.All()); got != 1 {
|
||||
t.Errorf("base registry mutated: got %d tools, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewContextPressureGate(t *testing.T) {
|
||||
g := NewContextPressureGate(100_000)
|
||||
|
||||
if g.ThresholdFraction != 0.5 {
|
||||
t.Errorf("ThresholdFraction = %v, want 0.5", g.ThresholdFraction)
|
||||
}
|
||||
if g.ContextWindowSize != 100_000 {
|
||||
t.Errorf("ContextWindowSize = %d, want 100000", g.ContextWindowSize)
|
||||
}
|
||||
if g.Mode() != DisclosureFull {
|
||||
t.Error("initial mode should be full disclosure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestContextPressureGateDisabled(t *testing.T) {
|
||||
g := NewContextPressureGate(0)
|
||||
g.Evaluate(nil)
|
||||
if g.Mode() != DisclosureFull {
|
||||
t.Error("disabled gate should always be full disclosure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestContextPressureGateSwitchesToBridge(t *testing.T) {
|
||||
g := NewContextPressureGate(1000)
|
||||
|
||||
tools := []ToolEntry{
|
||||
{
|
||||
Name: "big-tool",
|
||||
Description: strings.Repeat("x", 600),
|
||||
Handler: noopHandler,
|
||||
},
|
||||
}
|
||||
|
||||
g.Evaluate(tools)
|
||||
if g.Mode() != DisclosureBridge {
|
||||
t.Error("large schemas should trigger bridge mode")
|
||||
}
|
||||
}
|
||||
|
||||
func TestContextPressureGateStaysFull(t *testing.T) {
|
||||
g := NewContextPressureGate(100_000)
|
||||
|
||||
tools := []ToolEntry{
|
||||
{
|
||||
Name: "small-tool",
|
||||
Description: "A simple tool",
|
||||
Handler: noopHandler,
|
||||
},
|
||||
}
|
||||
|
||||
g.Evaluate(tools)
|
||||
if g.Mode() != DisclosureFull {
|
||||
t.Error("small schemas should keep full disclosure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestContextPressureGateAlwaysVisible(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
_ = r.Register(ToolEntry{Name: "essential", Handler: noopHandler, Description: "Always needed"})
|
||||
_ = r.Register(ToolEntry{Name: "optional", Handler: noopHandler, Description: strings.Repeat("x", 600)})
|
||||
|
||||
for _, e := range BridgeTools(r) {
|
||||
_ = r.Register(e)
|
||||
}
|
||||
|
||||
g := NewContextPressureGate(1000)
|
||||
g.SetAlwaysVisible("essential")
|
||||
|
||||
g.Evaluate(r.All())
|
||||
|
||||
if g.Mode() != DisclosureBridge {
|
||||
t.Fatal("expected bridge mode")
|
||||
}
|
||||
|
||||
filtered := g.FilterTools(r)
|
||||
names := make(map[string]bool)
|
||||
for _, e := range filtered {
|
||||
names[e.Name] = true
|
||||
}
|
||||
|
||||
if !names["essential"] {
|
||||
t.Error("essential tool should be always visible")
|
||||
}
|
||||
if !names[BridgeToolSearch] {
|
||||
t.Error("bridge tools should be visible in bridge mode")
|
||||
}
|
||||
if names["optional"] {
|
||||
t.Error("optional tool should not be visible in bridge mode")
|
||||
}
|
||||
}
|
||||
|
||||
func TestContextPressureGateReset(t *testing.T) {
|
||||
g := NewContextPressureGate(100)
|
||||
tools := []ToolEntry{
|
||||
{Name: "big", Description: strings.Repeat("x", 200), Handler: noopHandler},
|
||||
}
|
||||
|
||||
g.Evaluate(tools)
|
||||
if g.Mode() != DisclosureBridge {
|
||||
t.Fatal("expected bridge mode")
|
||||
}
|
||||
|
||||
g.Reset()
|
||||
if g.Mode() != DisclosureFull {
|
||||
t.Error("after reset, should be full disclosure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDisclosureModeString(t *testing.T) {
|
||||
if DisclosureFull.String() != "full" {
|
||||
t.Errorf("DisclosureFull = %q", DisclosureFull.String())
|
||||
}
|
||||
if DisclosureBridge.String() != "bridge" {
|
||||
t.Errorf("DisclosureBridge = %q", DisclosureBridge.String())
|
||||
}
|
||||
if DisclosureMode(99).String() != "unknown" {
|
||||
t.Errorf("unknown mode = %q", DisclosureMode(99).String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchesKeyword(t *testing.T) {
|
||||
e := ToolEntry{
|
||||
Name: "read_file",
|
||||
Toolset: "file",
|
||||
Description: "Read a file from disk",
|
||||
}
|
||||
|
||||
if !matchesKeyword(e, "file") {
|
||||
t.Error("should match by name")
|
||||
}
|
||||
if !matchesKeyword(e, "disk") {
|
||||
t.Error("should match by description")
|
||||
}
|
||||
if !matchesKeyword(e, "FILE") {
|
||||
t.Error("should match case-insensitive")
|
||||
}
|
||||
if matchesKeyword(e, "nonexistent") {
|
||||
t.Error("should not match")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTotalSchemaSize(t *testing.T) {
|
||||
tools := []ToolEntry{
|
||||
{
|
||||
Name: "tool-a",
|
||||
Description: "desc a",
|
||||
Schema: JSONSchema{
|
||||
"type": "object",
|
||||
"properties": JSONSchema{"x": JSONSchema{"type": "string"}},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
size := totalSchemaSize(tools)
|
||||
if size <= 0 {
|
||||
t.Error("schema size should be non-zero")
|
||||
}
|
||||
}
|
||||
@@ -1,319 +0,0 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDefaultGuardrailConfig(t *testing.T) {
|
||||
c := DefaultGuardrailConfig()
|
||||
|
||||
if c.ExactFailureWarnAfter != 3 {
|
||||
t.Errorf("ExactFailureWarnAfter = %d, want 3", c.ExactFailureWarnAfter)
|
||||
}
|
||||
if c.SameToolFailureWarnAfter != 5 {
|
||||
t.Errorf("SameToolFailureWarnAfter = %d, want 5", c.SameToolFailureWarnAfter)
|
||||
}
|
||||
if c.NoProgressWarnAfter != 10 {
|
||||
t.Errorf("NoProgressWarnAfter = %d, want 10", c.NoProgressWarnAfter)
|
||||
}
|
||||
if c.HardStopAfterWarnRepeat != 2 {
|
||||
t.Errorf("HardStopAfterWarnRepeat = %d, want 2", c.HardStopAfterWarnRepeat)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuardrailConfigValidate(t *testing.T) {
|
||||
t.Run("default config is valid", func(t *testing.T) {
|
||||
if err := DefaultGuardrailConfig().Validate(); err != nil {
|
||||
t.Errorf("default config should be valid: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("zero values are valid", func(t *testing.T) {
|
||||
// Zero means "never trigger" -- valid.
|
||||
if err := (ToolCallGuardrailConfig{}).Validate(); err != nil {
|
||||
t.Errorf("zero config should be valid: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("negative values are invalid", func(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
config ToolCallGuardrailConfig
|
||||
}{
|
||||
{"negative ExactFailureWarnAfter", ToolCallGuardrailConfig{ExactFailureWarnAfter: -1}},
|
||||
{"negative SameToolFailureWarnAfter", ToolCallGuardrailConfig{SameToolFailureWarnAfter: -1}},
|
||||
{"negative NoProgressWarnAfter", ToolCallGuardrailConfig{NoProgressWarnAfter: -1}},
|
||||
{"negative HardStopAfterWarnRepeat", ToolCallGuardrailConfig{HardStopAfterWarnRepeat: -1}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if err := tt.config.Validate(); err == nil {
|
||||
t.Error("expected error for negative value")
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// --- Guardrail decision engine tests ---
|
||||
|
||||
func TestGuardrailEngineAllow(t *testing.T) {
|
||||
// Below all thresholds -- should allow.
|
||||
g := NewGuardrailEngine(DefaultGuardrailConfig())
|
||||
|
||||
// A few successes -- no issues.
|
||||
g.RecordSuccess("tool-a")
|
||||
g.RecordSuccess("tool-b")
|
||||
g.RecordSuccess("tool-a")
|
||||
|
||||
if g.TotalCalls() != 3 {
|
||||
t.Errorf("TotalCalls = %d, want 3", g.TotalCalls())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuardrailEngineExactFailureWarn(t *testing.T) {
|
||||
config := ToolCallGuardrailConfig{
|
||||
ExactFailureWarnAfter: 2,
|
||||
HardStopAfterWarnRepeat: 99, // effectively never hard-stop
|
||||
}
|
||||
g := NewGuardrailEngine(config)
|
||||
|
||||
err := errors.New("connection refused")
|
||||
|
||||
// First failure -- allow.
|
||||
d := g.RecordFailure("tool-a", err)
|
||||
if d != DecisionAllow {
|
||||
t.Errorf("first failure should be allowed, got %v", d)
|
||||
}
|
||||
|
||||
// Second same failure -- warn.
|
||||
d = g.RecordFailure("tool-a", err)
|
||||
if d != DecisionWarn {
|
||||
t.Errorf("second same failure should warn, got %v", d)
|
||||
}
|
||||
|
||||
// Different error on same tool -- doesn't trigger exact-failure warn yet.
|
||||
d = g.RecordFailure("tool-a", errors.New("timeout"))
|
||||
if d != DecisionAllow {
|
||||
t.Errorf("different error should be allowed, got %v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuardrailEngineSameToolFailureWarn(t *testing.T) {
|
||||
config := ToolCallGuardrailConfig{
|
||||
SameToolFailureWarnAfter: 3,
|
||||
HardStopAfterWarnRepeat: 99,
|
||||
}
|
||||
g := NewGuardrailEngine(config)
|
||||
|
||||
// Three different errors on the same tool -- same-tool-failure triggers.
|
||||
g.RecordFailure("tool-a", errors.New("err1"))
|
||||
g.RecordFailure("tool-a", errors.New("err2"))
|
||||
d := g.RecordFailure("tool-a", errors.New("err3"))
|
||||
|
||||
if d != DecisionWarn {
|
||||
t.Errorf("third same-tool failure should warn, got %v", d)
|
||||
}
|
||||
|
||||
// A success resets the consecutive counter.
|
||||
g.RecordSuccess("tool-a")
|
||||
d = g.RecordFailure("tool-a", errors.New("err4"))
|
||||
if d != DecisionAllow {
|
||||
t.Errorf("after success, failure should be allow, got %v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuardrailEngineNoProgressWarn(t *testing.T) {
|
||||
config := ToolCallGuardrailConfig{
|
||||
NoProgressWarnAfter: 5,
|
||||
HardStopAfterWarnRepeat: 99,
|
||||
}
|
||||
g := NewGuardrailEngine(config)
|
||||
|
||||
for range 4 {
|
||||
g.RecordSuccess("tool-a")
|
||||
}
|
||||
|
||||
// 5th call -- warn (no progress).
|
||||
d := g.RecordSuccess("tool-a")
|
||||
if d != DecisionWarn {
|
||||
t.Errorf("5th call with no progress should warn, got %v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuardrailEngineMarkProgress(t *testing.T) {
|
||||
config := ToolCallGuardrailConfig{
|
||||
NoProgressWarnAfter: 5,
|
||||
}
|
||||
g := NewGuardrailEngine(config)
|
||||
|
||||
for range 4 {
|
||||
g.RecordSuccess("tool-a")
|
||||
}
|
||||
|
||||
// Mark progress resets the counter.
|
||||
g.MarkProgress()
|
||||
|
||||
d := g.RecordSuccess("tool-b")
|
||||
if d != DecisionAllow {
|
||||
t.Errorf("after MarkProgress, should be allow, got %v", d)
|
||||
}
|
||||
if g.TotalCalls() != 1 {
|
||||
t.Errorf("after MarkProgress, TotalCalls = %d, want 1", g.TotalCalls())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuardrailEngineHardStop(t *testing.T) {
|
||||
config := ToolCallGuardrailConfig{
|
||||
ExactFailureWarnAfter: 1,
|
||||
HardStopAfterWarnRepeat: 2,
|
||||
}
|
||||
g := NewGuardrailEngine(config)
|
||||
|
||||
err := errors.New("fatal")
|
||||
|
||||
// First failure -- warn.
|
||||
d := g.RecordFailure("tool-a", err)
|
||||
if d != DecisionWarn {
|
||||
t.Errorf("expected warn, got %v", d)
|
||||
}
|
||||
|
||||
// Second same failure -- hard-stop (warn repeat threshold reached).
|
||||
d = g.RecordFailure("tool-a", err)
|
||||
if d != DecisionHardStop {
|
||||
t.Errorf("expected hard-stop, got %v", d)
|
||||
}
|
||||
|
||||
if !g.HardStopped() {
|
||||
t.Error("HardStopped should be true")
|
||||
}
|
||||
|
||||
// All subsequent calls are hard-stop.
|
||||
d = g.RecordSuccess("tool-b")
|
||||
if d != DecisionHardStop {
|
||||
t.Errorf("after hard-stop, all calls should be hard-stop, got %v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuardrailEngineReset(t *testing.T) {
|
||||
config := ToolCallGuardrailConfig{
|
||||
ExactFailureWarnAfter: 1,
|
||||
HardStopAfterWarnRepeat: 1,
|
||||
}
|
||||
g := NewGuardrailEngine(config)
|
||||
|
||||
g.RecordFailure("tool-a", errors.New("err"))
|
||||
g.RecordFailure("tool-a", errors.New("err"))
|
||||
|
||||
if !g.HardStopped() {
|
||||
t.Fatal("expected hard-stopped")
|
||||
}
|
||||
|
||||
g.Reset()
|
||||
|
||||
if g.HardStopped() {
|
||||
t.Error("after reset, should not be hard-stopped")
|
||||
}
|
||||
if g.TotalCalls() != 0 {
|
||||
t.Errorf("after reset, TotalCalls = %d, want 0", g.TotalCalls())
|
||||
}
|
||||
|
||||
// Can record normally again.
|
||||
d := g.RecordSuccess("tool-b")
|
||||
if d != DecisionAllow {
|
||||
t.Errorf("after reset, should allow, got %v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuardrailDecisionString(t *testing.T) {
|
||||
tests := []struct {
|
||||
d GuardrailDecision
|
||||
want string
|
||||
}{
|
||||
{DecisionAllow, "allow"},
|
||||
{DecisionWarn, "warn"},
|
||||
{DecisionHardStop, "hard-stop"},
|
||||
{GuardrailDecision(99), "unknown"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := tt.d.String(); got != tt.want {
|
||||
t.Errorf("String() = %q, want %q", got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuardrailEngineConcurrent(t *testing.T) {
|
||||
// Use config with all thresholds effectively disabled to avoid
|
||||
// guardrail-induced short-circuits during concurrent stress.
|
||||
config := ToolCallGuardrailConfig{
|
||||
ExactFailureWarnAfter: 99999,
|
||||
SameToolFailureWarnAfter: 99999,
|
||||
NoProgressWarnAfter: 99999,
|
||||
HardStopAfterWarnRepeat: 0, // never hard-stop
|
||||
}
|
||||
g := NewGuardrailEngine(config)
|
||||
|
||||
done := make(chan struct{})
|
||||
for range 10 {
|
||||
go func() {
|
||||
for range 100 {
|
||||
g.RecordSuccess("tool")
|
||||
g.RecordFailure("tool", errors.New("err"))
|
||||
g.TotalCalls()
|
||||
g.HardStopped()
|
||||
}
|
||||
done <- struct{}{}
|
||||
}()
|
||||
}
|
||||
|
||||
for range 10 {
|
||||
<-done
|
||||
}
|
||||
|
||||
// Should not panic -- race detector will catch issues.
|
||||
if g.TotalCalls() != 1000*2 {
|
||||
t.Errorf("TotalCalls = %d, want 2000", g.TotalCalls())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuardrailEngineRecordFailureNilError(t *testing.T) {
|
||||
// Regression: RecordFailure used err.Error() without a nil check,
|
||||
// causing a nil-pointer dereference panic. After fix, nil error is
|
||||
// handled gracefully.
|
||||
g := NewGuardrailEngine(DefaultGuardrailConfig())
|
||||
|
||||
// Must not panic.
|
||||
d := g.RecordFailure("tool-a", nil)
|
||||
if d != DecisionAllow {
|
||||
t.Errorf("nil error should be DecisionAllow, got %v", d)
|
||||
}
|
||||
if g.TotalCalls() != 1 {
|
||||
t.Errorf("TotalCalls = %d, want 1 (call should still be counted)", g.TotalCalls())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuardrailEngineRecordFailureNilErrorDoesNotCountAsFailure(t *testing.T) {
|
||||
// Nil error is treated as "unknown failure" and does not increment
|
||||
// failure counters. Successive real failures should behave normally.
|
||||
config := ToolCallGuardrailConfig{
|
||||
ExactFailureWarnAfter: 2,
|
||||
}
|
||||
g := NewGuardrailEngine(config)
|
||||
|
||||
// Nil error — allowed, not counted toward exact-failure.
|
||||
g.RecordFailure("tool-a", nil)
|
||||
|
||||
// Real error — this is the first real failure.
|
||||
realErr := errors.New("real error")
|
||||
d := g.RecordFailure("tool-a", realErr)
|
||||
if d != DecisionAllow {
|
||||
t.Errorf("first real failure should be allowed, got %v", d)
|
||||
}
|
||||
|
||||
// Second real failure — should warn.
|
||||
d = g.RecordFailure("tool-a", realErr)
|
||||
if d != DecisionWarn {
|
||||
t.Errorf("second real failure should warn, got %v", d)
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package tools
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestListLimit(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input map[string]any
|
||||
def int
|
||||
max int
|
||||
want int
|
||||
}{
|
||||
{name: "absent", input: map[string]any{}, def: 20, max: 100, want: 20},
|
||||
{name: "zero", input: map[string]any{"limit": float64(0)}, def: 20, max: 100, want: 20},
|
||||
{name: "negative", input: map[string]any{"limit": float64(-5)}, def: 20, max: 100, want: 20},
|
||||
{name: "float64 within range", input: map[string]any{"limit": float64(42)}, def: 20, max: 100, want: 42},
|
||||
{name: "int within range", input: map[string]any{"limit": 7}, def: 20, max: 100, want: 7},
|
||||
{name: "clamped to max", input: map[string]any{"limit": float64(200)}, def: 20, max: 100, want: 100},
|
||||
{name: "exactly max", input: map[string]any{"limit": float64(100)}, def: 20, max: 100, want: 100},
|
||||
{name: "exactly def", input: map[string]any{"limit": float64(20)}, def: 20, max: 100, want: 20},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := ListLimit(tt.input, tt.def, tt.max); got != tt.want {
|
||||
t.Errorf("ListLimit() = %d, want %d", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,238 +0,0 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fakeSender is a Transport double that scripts responses by JSON-RPC
|
||||
// method name, so client tests never spawn a real subprocess. Safe for
|
||||
// concurrent use.
|
||||
type fakeSender struct {
|
||||
// responses maps a request method to the raw response body to return.
|
||||
responses map[string][]byte
|
||||
// errors maps a request method to an error to return instead.
|
||||
errors map[string]error
|
||||
|
||||
mu sync.Mutex
|
||||
// calls records every request body sent, in order.
|
||||
calls []Message
|
||||
}
|
||||
|
||||
func (f *fakeSender) Send(_ context.Context, body []byte) ([]byte, error) {
|
||||
var msg Message
|
||||
if err := json.Unmarshal(body, &msg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.calls = append(f.calls, msg)
|
||||
f.mu.Unlock()
|
||||
if err, ok := f.errors[msg.Method]; ok {
|
||||
return nil, err
|
||||
}
|
||||
if resp, ok := f.responses[msg.Method]; ok {
|
||||
return resp, nil
|
||||
}
|
||||
return nil, errors.New("fakeSender: no scripted response for method " + msg.Method)
|
||||
}
|
||||
|
||||
func (f *fakeSender) Notify(_ context.Context, body []byte) error {
|
||||
var msg Message
|
||||
if err := json.Unmarshal(body, &msg); err != nil {
|
||||
return err
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.calls = append(f.calls, msg)
|
||||
f.mu.Unlock()
|
||||
return f.errors[msg.Method]
|
||||
}
|
||||
|
||||
func newTestClient(f *fakeSender) *Client {
|
||||
return NewClient(f, "test-server", false)
|
||||
}
|
||||
|
||||
func TestInitializeSendsInitializeThenInitializedNotification(t *testing.T) {
|
||||
f := &fakeSender{
|
||||
responses: map[string][]byte{
|
||||
"initialize": []byte(`{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2024-11-05","serverInfo":{"name":"widget-server","version":"1.0.0"},"capabilities":{}}}`),
|
||||
},
|
||||
}
|
||||
c := newTestClient(f)
|
||||
|
||||
result, err := c.Initialize(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.ServerInfo.Name != "widget-server" {
|
||||
t.Errorf("ServerInfo.Name = %q, want widget-server", result.ServerInfo.Name)
|
||||
}
|
||||
if len(f.calls) != 2 {
|
||||
t.Fatalf("Send called %d times, want 2 (initialize + notifications/initialized)", len(f.calls))
|
||||
}
|
||||
methods := map[string]bool{}
|
||||
for _, call := range f.calls {
|
||||
methods[call.Method] = true
|
||||
}
|
||||
if !methods["initialize"] {
|
||||
t.Error("expected an initialize call")
|
||||
}
|
||||
if !methods["notifications/initialized"] {
|
||||
t.Error("expected a notifications/initialized call")
|
||||
}
|
||||
for _, call := range f.calls {
|
||||
if call.Method == "notifications/initialized" && len(call.ID) != 0 {
|
||||
t.Error("notifications/initialized must be a notification (no id)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitializeReturnsErrorOnTransportFailure(t *testing.T) {
|
||||
f := &fakeSender{errors: map[string]error{"initialize": errors.New("boom")}}
|
||||
c := newTestClient(f)
|
||||
|
||||
_, err := c.Initialize(context.Background())
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitializeReturnsErrorOnRPCError(t *testing.T) {
|
||||
f := &fakeSender{
|
||||
responses: map[string][]byte{
|
||||
"initialize": []byte(`{"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"init failed"}}`),
|
||||
},
|
||||
}
|
||||
c := newTestClient(f)
|
||||
|
||||
_, err := c.Initialize(context.Background())
|
||||
if err == nil {
|
||||
t.Fatal("expected error from RPC error response")
|
||||
}
|
||||
}
|
||||
|
||||
func TestListToolsParsesToolSchemas(t *testing.T) {
|
||||
f := &fakeSender{
|
||||
responses: map[string][]byte{
|
||||
"tools/list": []byte(`{"jsonrpc":"2.0","id":2,"result":{"tools":[
|
||||
{"name":"search_repos","description":"Search repositories","inputSchema":{"type":"object","properties":{"query":{"type":"string"}}}},
|
||||
{"name":"get_issue","description":"Get an issue","inputSchema":{"type":"object"}}
|
||||
]}}`),
|
||||
},
|
||||
}
|
||||
c := newTestClient(f)
|
||||
|
||||
toolList, err := c.ListTools(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(toolList) != 2 {
|
||||
t.Fatalf("ListTools returned %d tools, want 2", len(toolList))
|
||||
}
|
||||
if toolList[0].Name != "search_repos" {
|
||||
t.Errorf("tools[0].Name = %q, want search_repos", toolList[0].Name)
|
||||
}
|
||||
if toolList[0].InputSchema["type"] != "object" {
|
||||
t.Errorf("tools[0].InputSchema[type] = %v, want object", toolList[0].InputSchema["type"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestListToolsFollowsPaginationCursor(t *testing.T) {
|
||||
calls := 0
|
||||
// Two-page response: first call returns nextCursor, second returns none.
|
||||
page1 := []byte(`{"jsonrpc":"2.0","id":1,"result":{"tools":[{"name":"a","inputSchema":{}}],"nextCursor":"page2"}}`)
|
||||
page2 := []byte(`{"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"b","inputSchema":{}}]}}`)
|
||||
|
||||
c := NewClient(sendFunc(func(_ context.Context, body []byte) ([]byte, error) {
|
||||
calls++
|
||||
var msg Message
|
||||
_ = json.Unmarshal(body, &msg)
|
||||
var params struct {
|
||||
Cursor string `json:"cursor,omitempty"`
|
||||
}
|
||||
_ = json.Unmarshal(msg.Params, ¶ms)
|
||||
if params.Cursor == "" {
|
||||
return page1, nil
|
||||
}
|
||||
return page2, nil
|
||||
}), "test-server", false)
|
||||
|
||||
toolList, err := c.ListTools(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 2 {
|
||||
t.Fatalf("Send called %d times, want 2 (paginated)", calls)
|
||||
}
|
||||
if len(toolList) != 2 || toolList[0].Name != "a" || toolList[1].Name != "b" {
|
||||
t.Fatalf("ListTools = %+v, want [a b] across both pages", toolList)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallToolSendsNameAndArguments(t *testing.T) {
|
||||
f := &fakeSender{
|
||||
responses: map[string][]byte{
|
||||
"tools/call": []byte(`{"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"result text"}]}}`),
|
||||
},
|
||||
}
|
||||
c := newTestClient(f)
|
||||
|
||||
result, err := c.CallTool(context.Background(), "search_repos", map[string]any{"query": "widgets"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(result.Content) != 1 || result.Content[0].Text != "result text" {
|
||||
t.Fatalf("CallTool result = %+v", result)
|
||||
}
|
||||
|
||||
var params struct {
|
||||
Name string `json:"name"`
|
||||
Arguments map[string]any `json:"arguments"`
|
||||
}
|
||||
if err := json.Unmarshal(f.calls[0].Params, ¶ms); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if params.Name != "search_repos" {
|
||||
t.Errorf("params.Name = %q, want search_repos", params.Name)
|
||||
}
|
||||
if params.Arguments["query"] != "widgets" {
|
||||
t.Errorf("params.Arguments[query] = %v, want widgets", params.Arguments["query"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallToolReturnsIsErrorWithoutGoError(t *testing.T) {
|
||||
// Per MCP spec, a tool-level failure is reported via isError:true in a
|
||||
// successful JSON-RPC response, not a JSON-RPC error -- the LLM needs
|
||||
// to see the failure content, not just a Go error.
|
||||
f := &fakeSender{
|
||||
responses: map[string][]byte{
|
||||
"tools/call": []byte(`{"jsonrpc":"2.0","id":4,"result":{"content":[{"type":"text","text":"file not found"}],"isError":true}}`),
|
||||
},
|
||||
}
|
||||
c := newTestClient(f)
|
||||
|
||||
result, err := c.CallTool(context.Background(), "read_file", map[string]any{"path": "/nope"})
|
||||
if err != nil {
|
||||
t.Fatalf("CallTool returned Go error %v for a tool-level isError result", err)
|
||||
}
|
||||
if !result.IsError {
|
||||
t.Error("result.IsError = false, want true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestListToolsReturnsErrorOnMalformedResponse(t *testing.T) {
|
||||
f := &fakeSender{responses: map[string][]byte{"tools/list": []byte(`not json`)}}
|
||||
c := newTestClient(f)
|
||||
|
||||
if _, err := c.ListTools(context.Background()); err == nil {
|
||||
t.Fatal("expected error on malformed response")
|
||||
}
|
||||
}
|
||||
|
||||
// sendFunc adapts a function to the Transport interface.
|
||||
type sendFunc func(ctx context.Context, body []byte) ([]byte, error)
|
||||
|
||||
func (f sendFunc) Send(ctx context.Context, body []byte) ([]byte, error) { return f(ctx, body) }
|
||||
func (f sendFunc) Notify(context.Context, []byte) error { return nil }
|
||||
@@ -1,60 +0,0 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNpmCacheEnv(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
command string
|
||||
cacheDir string
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "npx gets a persistent cache",
|
||||
command: "npx",
|
||||
cacheDir: "/data/cache/mcp-npm",
|
||||
want: []string{
|
||||
"NPM_CONFIG_CACHE=/data/cache/mcp-npm",
|
||||
"NPM_CONFIG_PREFER_OFFLINE=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "an absolute path to npx still gets the persistent cache",
|
||||
command: "/usr/local/bin/npx",
|
||||
cacheDir: "/data/cache/mcp-npm",
|
||||
want: []string{
|
||||
"NPM_CONFIG_CACHE=/data/cache/mcp-npm",
|
||||
"NPM_CONFIG_PREFER_OFFLINE=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "a non-npx command has no npm registry dependency to fix",
|
||||
command: "/usr/local/bin/my-mcp-server",
|
||||
cacheDir: "/data/cache/mcp-npm",
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "empty command is left alone",
|
||||
command: "",
|
||||
cacheDir: "/data/cache/mcp-npm",
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "empty cacheDir is refused rather than caching into the process CWD",
|
||||
command: "npx",
|
||||
cacheDir: "",
|
||||
want: nil,
|
||||
},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
got := NpmCacheEnv(c.command, c.cacheDir)
|
||||
if !slices.Equal(got, c.want) {
|
||||
t.Errorf("NpmCacheEnv(%q, %q) = %v, want %v", c.command, c.cacheDir, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,252 +0,0 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// blockingSender is a Transport double whose Send blocks until release is
|
||||
// closed, so tests can observe whether multiple calls are in flight at
|
||||
// once (parallel) or one completes before the next starts (serialized).
|
||||
type blockingSender struct {
|
||||
release chan struct{}
|
||||
// entered receives one token per Send that starts, before that Send
|
||||
// blocks on release. A test counts the tokens to learn how many calls
|
||||
// the client allowed to overlap; unlike a sampled maximum, a token is
|
||||
// only ever sent by a call that really reached Send.
|
||||
entered chan struct{}
|
||||
|
||||
mu sync.Mutex
|
||||
inFlight int
|
||||
maxInFlight int
|
||||
}
|
||||
|
||||
func (b *blockingSender) Send(_ context.Context, body []byte) ([]byte, error) {
|
||||
b.mu.Lock()
|
||||
b.inFlight++
|
||||
if b.inFlight > b.maxInFlight {
|
||||
b.maxInFlight = b.inFlight
|
||||
}
|
||||
b.mu.Unlock()
|
||||
|
||||
if b.entered != nil {
|
||||
b.entered <- struct{}{}
|
||||
}
|
||||
<-b.release
|
||||
|
||||
b.mu.Lock()
|
||||
b.inFlight--
|
||||
b.mu.Unlock()
|
||||
|
||||
var msg Message
|
||||
_ = json.Unmarshal(body, &msg)
|
||||
return []byte(`{"jsonrpc":"2.0","id":` + string(msg.ID) + `,"result":{"content":[{"type":"text","text":"ok"}]}}`), nil
|
||||
}
|
||||
|
||||
func (b *blockingSender) Notify(context.Context, []byte) error { return nil }
|
||||
|
||||
func (b *blockingSender) MaxInFlight() int {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.maxInFlight
|
||||
}
|
||||
|
||||
// overlapWindow bounds how long a test gives calls to reach Send. A call
|
||||
// that is genuinely allowed to overlap reaches Send microseconds after its
|
||||
// goroutine starts, so a call still absent after this window is being held
|
||||
// back by the client, not by the scheduler.
|
||||
const overlapWindow = 500 * time.Millisecond
|
||||
|
||||
// enteredCount reports how many of n calls reached Send within window.
|
||||
func enteredCount(entered <-chan struct{}, n int, window time.Duration) int {
|
||||
count := 0
|
||||
for range n {
|
||||
select {
|
||||
case <-entered:
|
||||
count++
|
||||
case <-time.After(window):
|
||||
return count
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// TestCallToolParallelToolCallsControlsSameServerOverlap pins the per-server
|
||||
// flag: a server that has not opted in keeps one tools/call in flight, and a
|
||||
// server that opted in lets its calls overlap.
|
||||
func TestCallToolParallelToolCallsControlsSameServerOverlap(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
parallelToolCalls bool
|
||||
wantInFlight int
|
||||
}{
|
||||
{
|
||||
name: "server that has not opted in serializes tools/call",
|
||||
wantInFlight: 1,
|
||||
},
|
||||
{
|
||||
name: "opted-in server overlaps tools/call",
|
||||
parallelToolCalls: true,
|
||||
wantInFlight: 2,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
b := &blockingSender{entered: make(chan struct{}, 2), release: make(chan struct{})}
|
||||
c := NewClient(b, "test-server", tt.parallelToolCalls)
|
||||
|
||||
errs := make([]error, 2)
|
||||
started := make(chan struct{}, len(errs))
|
||||
var wg sync.WaitGroup
|
||||
for i := range errs {
|
||||
wg.Go(func() {
|
||||
started <- struct{}{}
|
||||
_, errs[i] = c.CallTool(context.Background(), "slow", nil)
|
||||
})
|
||||
}
|
||||
// Both callers are inside CallTool before either is measured, so
|
||||
// the count is what the client allowed, not the scheduler's.
|
||||
for range errs {
|
||||
<-started
|
||||
}
|
||||
|
||||
if got := enteredCount(b.entered, len(errs), overlapWindow); got != tt.wantInFlight {
|
||||
t.Fatalf("calls in flight at once = %d, want %d", got, tt.wantInFlight)
|
||||
}
|
||||
|
||||
close(b.release)
|
||||
wg.Wait()
|
||||
for i, err := range errs {
|
||||
if err != nil {
|
||||
t.Fatalf("call %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestParallelToolCallsIsPerServer pins the isolation half of the flag: one
|
||||
// server opting in must not un-serialize another server in the same process,
|
||||
// even while the opted-in server's own calls are overlapping.
|
||||
func TestParallelToolCallsIsPerServer(t *testing.T) {
|
||||
optedIn := &blockingSender{entered: make(chan struct{}, 2), release: make(chan struct{})}
|
||||
serialized := &blockingSender{entered: make(chan struct{}, 2), release: make(chan struct{})}
|
||||
parallel := NewClient(optedIn, "opted-in", true)
|
||||
sequential := NewClient(serialized, "default", false)
|
||||
|
||||
call := func(c *Client) {
|
||||
if _, err := c.CallTool(context.Background(), "slow", nil); err != nil {
|
||||
t.Errorf("CallTool: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
var parallelWG sync.WaitGroup
|
||||
for range 2 {
|
||||
parallelWG.Go(func() { call(parallel) })
|
||||
}
|
||||
if got := enteredCount(optedIn.entered, 2, overlapWindow); got != 2 {
|
||||
t.Fatalf("opted-in server calls in flight = %d, want 2", got)
|
||||
}
|
||||
|
||||
// The opted-in server's calls are still open when the other server is
|
||||
// measured, so a leak of its parallelism would show up here.
|
||||
var sequentialWG sync.WaitGroup
|
||||
for range 2 {
|
||||
sequentialWG.Go(func() { call(sequential) })
|
||||
}
|
||||
if got := enteredCount(serialized.entered, 2, overlapWindow); got != 1 {
|
||||
t.Fatalf("server that did not opt in calls in flight = %d, want 1: opting one server in must not free another server's calls", got)
|
||||
}
|
||||
|
||||
close(optedIn.release)
|
||||
close(serialized.release)
|
||||
parallelWG.Wait()
|
||||
sequentialWG.Wait()
|
||||
}
|
||||
|
||||
func TestCallToolSerializesByDefault(t *testing.T) {
|
||||
b := &blockingSender{release: make(chan struct{})}
|
||||
c := NewClient(b, "test-server", false)
|
||||
|
||||
const n = 5
|
||||
var wg sync.WaitGroup
|
||||
for range n {
|
||||
wg.Go(func() {
|
||||
_, _ = c.CallTool(context.Background(), "slow", nil)
|
||||
})
|
||||
}
|
||||
|
||||
// Give goroutines a moment to reach Send; with serialization, only one
|
||||
// should ever be blocked in Send at a time.
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if got := b.MaxInFlight(); got > 1 {
|
||||
t.Errorf("MaxInFlight = %d, want 1 (default is serialized)", got)
|
||||
}
|
||||
|
||||
close(b.release)
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestCallToolSerializedStillCompletesAllCalls(t *testing.T) {
|
||||
b := &blockingSender{release: make(chan struct{})}
|
||||
close(b.release) // never actually blocks -- just verifying correctness, not timing
|
||||
c := NewClient(b, "test-server", false)
|
||||
|
||||
const n = 10
|
||||
var completed atomic.Int32
|
||||
var wg sync.WaitGroup
|
||||
for range n {
|
||||
wg.Go(func() {
|
||||
if _, err := c.CallTool(context.Background(), "fast", nil); err == nil {
|
||||
completed.Add(1)
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
if got := completed.Load(); got != n {
|
||||
t.Errorf("completed = %d, want %d", got, n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallToolSerializationDoesNotBlockDifferentClients(t *testing.T) {
|
||||
// Serialization is per-Client (per-server), not global -- two
|
||||
// independent Clients (different servers) must not block each other.
|
||||
b1 := &blockingSender{release: make(chan struct{})}
|
||||
b2 := &blockingSender{release: make(chan struct{})}
|
||||
close(b2.release) // c2's own call should complete immediately, unblocked
|
||||
c1 := NewClient(b1, "server-1", false)
|
||||
c2 := NewClient(b2, "server-2", false)
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
_, _ = c1.CallTool(context.Background(), "slow", nil)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
// c1's call is now blocked in Send. c2 must still be able to proceed
|
||||
// immediately -- it has its own serialization lock.
|
||||
select {
|
||||
case <-done:
|
||||
t.Fatal("c1's call should still be blocked")
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
|
||||
c2Done := make(chan struct{})
|
||||
go func() {
|
||||
_, _ = c2.CallTool(context.Background(), "fast", nil)
|
||||
close(c2Done)
|
||||
}()
|
||||
select {
|
||||
case <-c2Done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("c2's call should not be blocked by c1's in-flight call")
|
||||
}
|
||||
|
||||
close(b1.release)
|
||||
<-done
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// samplingRouterTransport is a Transport double that also receives
|
||||
// server-initiated requests, so the client's dispatch can be tested without
|
||||
// a subprocess. It captures the handler the client registers.
|
||||
type samplingRouterTransport struct {
|
||||
mu sync.Mutex
|
||||
handler ServerRequestHandler
|
||||
}
|
||||
|
||||
func (t *samplingRouterTransport) Send(context.Context, []byte) ([]byte, error) {
|
||||
return nil, errors.New("samplingRouterTransport: Send is not used by these tests")
|
||||
}
|
||||
|
||||
func (t *samplingRouterTransport) Notify(context.Context, []byte) error { return nil }
|
||||
|
||||
func (t *samplingRouterTransport) SetServerRequestHandler(handler ServerRequestHandler) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.handler = handler
|
||||
}
|
||||
|
||||
func (t *samplingRouterTransport) registered() ServerRequestHandler {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return t.handler
|
||||
}
|
||||
|
||||
func samplingParams(t *testing.T) json.RawMessage {
|
||||
t.Helper()
|
||||
return json.RawMessage(`{"messages":[{"role":"user","content":{"type":"text","text":"2+2?"}}],"maxTokens":16}`)
|
||||
}
|
||||
|
||||
func TestServerSamplingRequestIsAnswered(t *testing.T) {
|
||||
transport := &samplingRouterTransport{}
|
||||
var got SamplingRequest
|
||||
NewClient(transport, "sampling-server", false, WithSamplingHandler(
|
||||
func(_ context.Context, req SamplingRequest) (SamplingResult, error) {
|
||||
got = req
|
||||
return SamplingResult{
|
||||
Model: "openai/gpt-5.6",
|
||||
Role: "assistant",
|
||||
Content: SamplingContent{Type: "text", Text: "four"},
|
||||
StopReason: "stop",
|
||||
}, nil
|
||||
},
|
||||
))
|
||||
|
||||
handler := transport.registered()
|
||||
if handler == nil {
|
||||
t.Fatal("client did not register a server request handler with the transport")
|
||||
}
|
||||
|
||||
result, rpcErr := handler(context.Background(), "sampling/createMessage", samplingParams(t))
|
||||
if rpcErr != nil {
|
||||
t.Fatalf("sampling request answered with RPC error %+v, want a result", rpcErr)
|
||||
}
|
||||
if len(got.Messages) != 1 || got.Messages[0].Content.Text != "2+2?" {
|
||||
t.Errorf("handler received %+v, want the request's message text", got)
|
||||
}
|
||||
if got.MaxTokens != 16 {
|
||||
t.Errorf("handler received maxTokens %d, want 16", got.MaxTokens)
|
||||
}
|
||||
|
||||
var decoded SamplingResult
|
||||
if err := json.Unmarshal(result, &decoded); err != nil {
|
||||
t.Fatalf("unmarshal sampling result: %v", err)
|
||||
}
|
||||
if decoded.Content.Text != "four" || decoded.Model != "openai/gpt-5.6" {
|
||||
t.Errorf("sampling result = %+v, want the handler's completion", decoded)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerSamplingRequestWithoutHandlerIsMethodNotFound(t *testing.T) {
|
||||
transport := &samplingRouterTransport{}
|
||||
NewClient(transport, "sampling-server", false)
|
||||
|
||||
handler := transport.registered()
|
||||
if handler == nil {
|
||||
t.Fatal("client did not register a server request handler with the transport")
|
||||
}
|
||||
|
||||
_, rpcErr := handler(context.Background(), "sampling/createMessage", samplingParams(t))
|
||||
if rpcErr == nil {
|
||||
t.Fatal("sampling request with no configured handler returned a result, want a JSON-RPC error")
|
||||
}
|
||||
if rpcErr.Code != ErrCodeMethodNotFound {
|
||||
t.Errorf("error code = %d, want %d (method not found)", rpcErr.Code, ErrCodeMethodNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerSamplingHandlerFailureIsInternalError(t *testing.T) {
|
||||
transport := &samplingRouterTransport{}
|
||||
NewClient(transport, "sampling-server", false, WithSamplingHandler(
|
||||
func(context.Context, SamplingRequest) (SamplingResult, error) {
|
||||
return SamplingResult{}, errors.New("model unavailable")
|
||||
},
|
||||
))
|
||||
|
||||
_, rpcErr := transport.registered()(context.Background(), "sampling/createMessage", samplingParams(t))
|
||||
if rpcErr == nil {
|
||||
t.Fatal("handler failure returned a result, want a JSON-RPC error")
|
||||
}
|
||||
if rpcErr.Code != ErrCodeInternal {
|
||||
t.Errorf("error code = %d, want %d (internal)", rpcErr.Code, ErrCodeInternal)
|
||||
}
|
||||
if !strings.Contains(rpcErr.Message, "model unavailable") {
|
||||
t.Errorf("error message = %q, want the handler's own error text", rpcErr.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerUnknownRequestIsMethodNotFound(t *testing.T) {
|
||||
transport := &samplingRouterTransport{}
|
||||
NewClient(transport, "sampling-server", false, WithSamplingHandler(
|
||||
func(context.Context, SamplingRequest) (SamplingResult, error) {
|
||||
t.Error("sampling handler must not run for an unknown method")
|
||||
return SamplingResult{}, nil
|
||||
},
|
||||
))
|
||||
|
||||
_, rpcErr := transport.registered()(context.Background(), "roots/list", json.RawMessage(`{}`))
|
||||
if rpcErr == nil || rpcErr.Code != ErrCodeMethodNotFound {
|
||||
t.Fatalf("unknown method error = %+v, want method not found", rpcErr)
|
||||
}
|
||||
}
|
||||
|
||||
type nopWriteCloser struct{ io.Writer }
|
||||
|
||||
func (nopWriteCloser) Close() error { return nil }
|
||||
|
||||
// TestStdioTransportAnswersServerSamplingRequest drives the transport's
|
||||
// reader directly: a server-initiated frame read off stdout must reach the
|
||||
// handler and its response must be written back to stdin with the server's
|
||||
// own request id, or the server hangs waiting for a completion it never
|
||||
// gets.
|
||||
func TestStdioTransportAnswersServerSamplingRequest(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
transport := NewStdioTransport(StdioTransportConfig{Command: "unused"})
|
||||
transport.stdin = nopWriteCloser{&out}
|
||||
// No subprocess is spawned here: the reader path under test only writes a
|
||||
// response when the transport considers itself live.
|
||||
transport.mu.Lock()
|
||||
transport.state = StateRunning
|
||||
transport.mu.Unlock()
|
||||
|
||||
handled := make(chan SamplingRequest, 1)
|
||||
transport.SetServerRequestHandler(
|
||||
func(_ context.Context, method string, params json.RawMessage) (json.RawMessage, *ErrorData) {
|
||||
if method != "sampling/createMessage" {
|
||||
return nil, &ErrorData{Code: ErrCodeMethodNotFound, Message: method}
|
||||
}
|
||||
var req SamplingRequest
|
||||
if err := json.Unmarshal(params, &req); err != nil {
|
||||
return nil, &ErrorData{Code: ErrCodeInvalidParams, Message: err.Error()}
|
||||
}
|
||||
handled <- req
|
||||
body, err := json.Marshal(SamplingResult{
|
||||
Model: "openai/gpt-5.6",
|
||||
Role: "assistant",
|
||||
Content: SamplingContent{Type: "text", Text: "four"},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, &ErrorData{Code: ErrCodeInternal, Message: err.Error()}
|
||||
}
|
||||
return body, nil
|
||||
},
|
||||
)
|
||||
|
||||
transport.deliverResponse(t.Context(), []byte(
|
||||
`{"jsonrpc":"2.0","id":42,"method":"sampling/createMessage",`+
|
||||
`"params":{"messages":[{"role":"user","content":{"type":"text","text":"ping"}}]}}`,
|
||||
))
|
||||
|
||||
select {
|
||||
case req := <-handled:
|
||||
if len(req.Messages) != 1 || req.Messages[0].Content.Text != "ping" {
|
||||
t.Errorf("handler received %+v, want the request's message text", req)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("server sampling request was not routed to the handler")
|
||||
}
|
||||
|
||||
// The handler goroutine writes the response after it returns; wait for it
|
||||
// before reading the shared buffer.
|
||||
transport.serverRequestWg.Wait()
|
||||
if !strings.Contains(out.String(), `"id":42`) {
|
||||
t.Fatalf("stdio transport did not write a response for request id 42; wrote %q", out.String())
|
||||
}
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestHTTPTransportSendReturnsResponse(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
t.Errorf("expected POST, got %s", r.Method)
|
||||
}
|
||||
if ct := r.Header.Get("Content-Type"); ct != "application/json" {
|
||||
t.Errorf("Content-Type = %q, want application/json", ct)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = fmt.Fprint(w, `{"jsonrpc":"2.0","id":"1","result":{"status":"ok"}}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
tr := NewHTTPTransport(HTTPTransportConfig{Endpoint: srv.URL})
|
||||
resp, err := tr.Send(context.Background(), []byte(`{"jsonrpc":"2.0","id":"1","method":"test","params":{}}`))
|
||||
if err != nil {
|
||||
t.Fatalf("Send: %v", err)
|
||||
}
|
||||
var msg Message
|
||||
if err := json.Unmarshal(resp, &msg); err != nil {
|
||||
t.Fatalf("parse response: %v", err)
|
||||
}
|
||||
if string(msg.Result) != `{"status":"ok"}` {
|
||||
t.Errorf("result = %s, want {\"status\":\"ok\"}", msg.Result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPTransportSendReturnsErrorOnNon200(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = fmt.Fprint(w, "boom")
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
tr := NewHTTPTransport(HTTPTransportConfig{Endpoint: srv.URL})
|
||||
_, err := tr.Send(context.Background(), []byte(`{"jsonrpc":"2.0","id":"1","method":"test"}`))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for 500 response")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "500") {
|
||||
t.Errorf("error = %v, want it to mention status 500", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPTransportSendReturnsErrorOnConnectionRefused(t *testing.T) {
|
||||
tr := NewHTTPTransport(HTTPTransportConfig{Endpoint: "http://127.0.0.1:1"}) // nothing listening
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
_, err := tr.Send(ctx, []byte(`{"jsonrpc":"2.0","id":"1","method":"test"}`))
|
||||
if err == nil {
|
||||
t.Fatal("expected connection error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPTransportSendHonorsContext(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
tr := NewHTTPTransport(HTTPTransportConfig{Endpoint: srv.URL})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
|
||||
defer cancel()
|
||||
_, err := tr.Send(ctx, []byte(`{"jsonrpc":"2.0","id":"1","method":"test"}`))
|
||||
if err == nil {
|
||||
t.Fatal("expected context deadline error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPTransportNotifyWritesWithoutWaitingForResponse(t *testing.T) {
|
||||
notified := make(chan struct{})
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
close(notified)
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
tr := NewHTTPTransport(HTTPTransportConfig{Endpoint: srv.URL})
|
||||
err := tr.Notify(context.Background(), []byte(`{"jsonrpc":"2.0","method":"initialized"}`))
|
||||
if err != nil {
|
||||
t.Fatalf("Notify: %v", err)
|
||||
}
|
||||
select {
|
||||
case <-notified:
|
||||
// expected
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("notification was not delivered")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPTransportSendWithCustomHeaders(t *testing.T) {
|
||||
var receivedHeader string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
receivedHeader = r.Header.Get("Authorization")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = fmt.Fprint(w, `{"jsonrpc":"2.0","id":"1","result":{}}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
tr := NewHTTPTransport(HTTPTransportConfig{
|
||||
Endpoint: srv.URL,
|
||||
Headers: map[string]string{"Authorization": "Bearer secret"},
|
||||
})
|
||||
_, err := tr.Send(context.Background(), []byte(`{"jsonrpc":"2.0","id":"1","method":"test"}`))
|
||||
if err != nil {
|
||||
t.Fatalf("Send: %v", err)
|
||||
}
|
||||
if receivedHeader != "Bearer secret" {
|
||||
t.Errorf("Authorization header = %q, want Bearer secret", receivedHeader)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPTransportConfigDefaults(t *testing.T) {
|
||||
cfg := HTTPTransportConfig{}
|
||||
timeout := cfg.effectiveTimeout()
|
||||
if timeout != 30*time.Second {
|
||||
t.Errorf("default timeout = %v, want 30s", timeout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPTransportStateAlwaysRunning(t *testing.T) {
|
||||
tr := NewHTTPTransport(HTTPTransportConfig{Endpoint: "http://localhost"})
|
||||
if state := tr.State(); state != StateRunning {
|
||||
t.Errorf("State() = %v, want StateRunning", state)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPTransportStartStopAreNoops(t *testing.T) {
|
||||
tr := NewHTTPTransport(HTTPTransportConfig{Endpoint: "http://localhost"})
|
||||
ctx := context.Background()
|
||||
// Start and Stop must not error.
|
||||
if err := tr.Start(ctx); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
// State remains Running after Start.
|
||||
if state := tr.State(); state != StateRunning {
|
||||
t.Errorf("State after Start = %v, want StateRunning", state)
|
||||
}
|
||||
if err := tr.Stop(ctx); err != nil {
|
||||
t.Fatalf("Stop: %v", err)
|
||||
}
|
||||
// State remains Running after Stop (stateless transport).
|
||||
if state := tr.State(); state != StateRunning {
|
||||
t.Errorf("State after Stop = %v, want StateRunning", state)
|
||||
}
|
||||
}
|
||||
@@ -1,332 +0,0 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// sseTestServer creates a fake MCP server that speaks the SSE transport
|
||||
// protocol: GET /sse for the event stream, POST /messages for client→server.
|
||||
// handleMessage receives each posted JSON-RPC body; callers can enqueue
|
||||
// events onto events to send them back through the SSE stream.
|
||||
type sseTestServer struct {
|
||||
*httptest.Server
|
||||
SessID string
|
||||
events chan string
|
||||
incoming chan []byte
|
||||
}
|
||||
|
||||
func newSSETestServer(t *testing.T) *sseTestServer {
|
||||
t.Helper()
|
||||
s := &sseTestServer{
|
||||
events: make(chan string, 10),
|
||||
incoming: make(chan []byte, 10),
|
||||
}
|
||||
s.Server = httptest.NewUnstartedServer(s)
|
||||
s.Start()
|
||||
s.SessID = "test-session-id"
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *sseTestServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/sse":
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "no flusher", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
// Send the endpoint event — tells the client where to POST.
|
||||
_, _ = fmt.Fprintf(w, "event: endpoint\ndata: %s/messages?session_id=%s\n\n", s.URL, s.SessID)
|
||||
flusher.Flush()
|
||||
|
||||
for {
|
||||
select {
|
||||
case data := <-s.events:
|
||||
_, _ = fmt.Fprintf(w, "event: message\ndata: %s\n\n", data)
|
||||
flusher.Flush()
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
case "/messages":
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
_ = r.Body.Close()
|
||||
s.incoming <- body
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSETransportSendReceivesResponseViaSSE(t *testing.T) {
|
||||
fake := newSSETestServer(t)
|
||||
defer fake.Close()
|
||||
|
||||
tr := NewSSETransport(SSETransportConfig{
|
||||
SSEEndpoint: fake.URL + "/sse",
|
||||
MessageEndpoint: fake.URL + "/messages",
|
||||
})
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
defer func() { _ = tr.Stop(context.Background()) }()
|
||||
|
||||
time.Sleep(50 * time.Millisecond) // let the SSE connection establish
|
||||
|
||||
// Send a request. The fake server will enqueue it; we then send
|
||||
// the response back through the SSE event channel.
|
||||
go func() {
|
||||
<-fake.incoming // wait for the POST
|
||||
fake.events <- `{"jsonrpc":"2.0","id":42,"result":{"from_sse":true}}`
|
||||
}()
|
||||
|
||||
resp, err := tr.Send(context.Background(), []byte(`{"jsonrpc":"2.0","id":42,"method":"test","params":{}}`))
|
||||
if err != nil {
|
||||
t.Fatalf("Send: %v", err)
|
||||
}
|
||||
var msg Message
|
||||
if err := json.Unmarshal(resp, &msg); err != nil {
|
||||
t.Fatalf("parse: %v", err)
|
||||
}
|
||||
if string(msg.Result) != `{"from_sse":true}` {
|
||||
t.Errorf("result = %s", msg.Result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSETransportNotifyFireAndForget(t *testing.T) {
|
||||
fake := newSSETestServer(t)
|
||||
defer fake.Close()
|
||||
|
||||
tr := NewSSETransport(SSETransportConfig{
|
||||
SSEEndpoint: fake.URL + "/sse",
|
||||
MessageEndpoint: fake.URL + "/messages",
|
||||
})
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
defer func() { _ = tr.Stop(context.Background()) }()
|
||||
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
err := tr.Notify(context.Background(), []byte(`{"jsonrpc":"2.0","method":"initialized"}`))
|
||||
if err != nil {
|
||||
t.Fatalf("Notify: %v", err)
|
||||
}
|
||||
select {
|
||||
case <-fake.incoming:
|
||||
// notification delivered
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("notification not delivered")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSETransportStartFailsOnBadSSEEndpoint(t *testing.T) {
|
||||
tr := NewSSETransport(SSETransportConfig{
|
||||
SSEEndpoint: "http://127.0.0.1:1/sse",
|
||||
MessageEndpoint: "http://127.0.0.1:1/messages",
|
||||
})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := tr.Start(ctx); err == nil {
|
||||
t.Fatal("expected connection error on Start")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSETransportStopClosesConnectionAndFailsPending(t *testing.T) {
|
||||
fake := newSSETestServer(t)
|
||||
defer fake.Close()
|
||||
|
||||
tr := NewSSETransport(SSETransportConfig{
|
||||
SSEEndpoint: fake.URL + "/sse",
|
||||
MessageEndpoint: fake.URL + "/messages",
|
||||
})
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
if err := tr.Stop(context.Background()); err != nil {
|
||||
t.Fatalf("Stop: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSETransportSendFailsWhenStopped(t *testing.T) {
|
||||
tr := NewSSETransport(SSETransportConfig{
|
||||
SSEEndpoint: "http://127.0.0.1:1/sse",
|
||||
MessageEndpoint: "http://127.0.0.1:1/messages",
|
||||
})
|
||||
_, err := tr.Send(context.Background(), []byte(`{"jsonrpc":"2.0","id":"1","method":"test"}`))
|
||||
if err == nil || !strings.Contains(err.Error(), "not running") {
|
||||
t.Errorf("err = %v, want 'not running' error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSETransportConfigDefaults(t *testing.T) {
|
||||
cfg := SSETransportConfig{}
|
||||
if cfg.effectiveReconnectBackoff() == 0 {
|
||||
t.Error("reconnect backoff should have a default")
|
||||
}
|
||||
if cfg.effectiveMaxReconnectBackoff() == 0 {
|
||||
t.Error("max reconnect backoff should have a default")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSETransportStateReflectsRunning(t *testing.T) {
|
||||
fake := newSSETestServer(t)
|
||||
defer fake.Close()
|
||||
|
||||
tr := NewSSETransport(SSETransportConfig{
|
||||
SSEEndpoint: fake.URL + "/sse",
|
||||
MessageEndpoint: fake.URL + "/messages",
|
||||
})
|
||||
|
||||
// Before Start, state should be StateStopped.
|
||||
if state := tr.State(); state != StateStopped {
|
||||
t.Errorf("State before Start = %v, want StateStopped", state)
|
||||
}
|
||||
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
|
||||
// After Start, state should be StateRunning.
|
||||
if state := tr.State(); state != StateRunning {
|
||||
t.Errorf("State after Start = %v, want StateRunning", state)
|
||||
}
|
||||
|
||||
if err := tr.Stop(context.Background()); err != nil {
|
||||
t.Fatalf("Stop: %v", err)
|
||||
}
|
||||
|
||||
// After Stop, state should be StateStopped.
|
||||
if state := tr.State(); state != StateStopped {
|
||||
t.Errorf("State after Stop = %v, want StateStopped", state)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSETransportConcurrentSendsGetCorrectResponses(t *testing.T) {
|
||||
fake := newSSETestServer(t)
|
||||
defer fake.Close()
|
||||
|
||||
tr := NewSSETransport(SSETransportConfig{
|
||||
SSEEndpoint: fake.URL + "/sse",
|
||||
MessageEndpoint: fake.URL + "/messages",
|
||||
})
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
defer func() { _ = tr.Stop(context.Background()) }()
|
||||
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
// Send 5 concurrent requests. The fake server reads them all from
|
||||
// the incoming channel, then sends responses back through SSE.
|
||||
const n = 5
|
||||
var wg sync.WaitGroup
|
||||
results := make(chan error, n)
|
||||
|
||||
for i := range n {
|
||||
wg.Add(1)
|
||||
go func(id int) {
|
||||
defer wg.Done()
|
||||
resp, err := tr.Send(context.Background(),
|
||||
fmt.Appendf(nil, `{"jsonrpc":"2.0","id":%d,"method":"test"}`, id))
|
||||
if err != nil {
|
||||
results <- fmt.Errorf("id %d: Send: %w", id, err)
|
||||
return
|
||||
}
|
||||
var msg Message
|
||||
if err := json.Unmarshal(resp, &msg); err != nil {
|
||||
results <- fmt.Errorf("id %d: parse: %w", id, err)
|
||||
return
|
||||
}
|
||||
if string(msg.ID) != fmt.Sprintf("%d", id) {
|
||||
results <- fmt.Errorf("response ID = %s, want %d", msg.ID, id)
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
|
||||
// Drain incoming POSTs and feed responses back in order.
|
||||
for i := range n {
|
||||
body := <-fake.incoming
|
||||
var env struct {
|
||||
ID int `json:"id"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &env)
|
||||
fake.events <- fmt.Sprintf(`{"jsonrpc":"2.0","id":%d,"result":{"ok":true}}`, env.ID)
|
||||
_ = i
|
||||
}
|
||||
wg.Wait()
|
||||
close(results)
|
||||
for e := range results {
|
||||
t.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSETransportStopCancelsInFlightReconnect pins the Stop contract: when
|
||||
// the SSE stream drops and reconnect is blocked on an unreachable endpoint,
|
||||
// Stop must cancel that in-flight HTTP request instead of waiting for the
|
||||
// OS-level connect/read to time out.
|
||||
func TestSSETransportStopCancelsInFlightReconnect(t *testing.T) {
|
||||
var requests atomic.Int32
|
||||
reconnectStarted := make(chan struct{})
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch requests.Add(1) {
|
||||
case 1:
|
||||
// Initial connect: deliver the endpoint event, then return so the
|
||||
// client reader sees EOF and drops into reconnect.
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = fmt.Fprintf(w, "event: endpoint\ndata: http://127.0.0.1:1/messages\n\n")
|
||||
if f, ok := w.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
}
|
||||
default:
|
||||
// Reconnect: block until the client cancels the request (via Stop).
|
||||
close(reconnectStarted)
|
||||
<-r.Context().Done()
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
tr := NewSSETransport(SSETransportConfig{
|
||||
SSEEndpoint: srv.URL + "/sse",
|
||||
ReconnectBackoff: time.Millisecond,
|
||||
MaxReconnectBackoff: time.Millisecond,
|
||||
})
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case <-reconnectStarted:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("reconnect request never started")
|
||||
}
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- tr.Stop(context.Background()) }()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("Stop: %v", err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Stop did not cancel the in-flight reconnect request")
|
||||
}
|
||||
}
|
||||
@@ -1,907 +0,0 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ── Helper: test MCP server process ─────────────────────────────────────
|
||||
|
||||
// TestMCPServerHelper is the entry point for the test helper subprocess.
|
||||
// It is NOT a test -- it is a process invoked by StdioTransport tests.
|
||||
// It must be the only Test* function in this file that runs as a subprocess;
|
||||
// we guard it with GO_WANT_MCP_HELPER.
|
||||
func TestMCPServerHelper(t *testing.T) {
|
||||
if os.Getenv("GO_WANT_MCP_HELPER") != "1" {
|
||||
return
|
||||
}
|
||||
behavior := os.Getenv("MCP_HELPER_BEHAVIOR")
|
||||
srv := &testMCPServer{behavior: behavior}
|
||||
if err := srv.serve(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(2)
|
||||
}
|
||||
runtime.Goexit()
|
||||
}
|
||||
|
||||
// testMCPServer reads MCP messages from stdin and responds.
|
||||
type testMCPServer struct {
|
||||
behavior string
|
||||
}
|
||||
|
||||
func (s *testMCPServer) serve() error {
|
||||
// crash-after-init must exit immediately on startup, before the read
|
||||
// loop, so the transport sees a subprocess that dies right after spawn.
|
||||
if s.behavior == "crash-after-init" {
|
||||
syscall.Exit(1)
|
||||
}
|
||||
|
||||
// Use a persistent bufio.Reader so buffered bytes between calls
|
||||
// are not lost (each readMessage call checks for an existing bufio.Reader).
|
||||
stdin := bufio.NewReader(os.Stdin)
|
||||
for {
|
||||
body, err := readMessage(stdin)
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrClosedPipe) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("read: %w", err)
|
||||
}
|
||||
|
||||
var msg Message
|
||||
if err := json.Unmarshal(body, &msg); err != nil {
|
||||
return fmt.Errorf("unmarshal: %w", err)
|
||||
}
|
||||
|
||||
resp, err := s.handle(msg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp != nil {
|
||||
data, _ := json.Marshal(resp)
|
||||
if err := writeMessage(os.Stdout, data); err != nil {
|
||||
return fmt.Errorf("write: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *testMCPServer) handle(msg Message) (*Message, error) {
|
||||
if len(msg.ID) == 0 {
|
||||
// A notification -- no response expected. Record it so a
|
||||
// subsequent request's echo can report whether one arrived.
|
||||
notificationsReceived.Add(1)
|
||||
return nil, nil
|
||||
}
|
||||
switch s.behavior {
|
||||
case "hang-on-start":
|
||||
// Respond to initialize then hang (no more output)
|
||||
if msg.Method == "initialize" {
|
||||
return &Message{
|
||||
JSONRPC: "2.0",
|
||||
ID: msg.ID,
|
||||
Result: json.RawMessage(`{"protocolVersion":"2025-03-26","capabilities":{}}`),
|
||||
}, nil
|
||||
}
|
||||
return nil, nil
|
||||
|
||||
case "slow-response":
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
return s.echo(msg), nil
|
||||
|
||||
case "bad-framing":
|
||||
// Write malformed output without MCP's required trailing newline and
|
||||
// exit immediately so the client observes an incomplete frame.
|
||||
_, _ = fmt.Fprint(os.Stdout, `{"jsonrpc":"2.0","id":1,"result":{}}`)
|
||||
syscall.Exit(0)
|
||||
return nil, nil
|
||||
|
||||
default:
|
||||
return s.echo(msg), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *testMCPServer) echo(msg Message) *Message {
|
||||
cwd, _ := os.Getwd()
|
||||
result, _ := json.Marshal(map[string]any{
|
||||
"echoed": msg.Method,
|
||||
"notifications_received": notificationsReceived.Load(),
|
||||
"cwd": cwd,
|
||||
})
|
||||
return &Message{
|
||||
JSONRPC: "2.0",
|
||||
ID: msg.ID,
|
||||
Result: result,
|
||||
}
|
||||
}
|
||||
|
||||
// notificationsReceived counts notifications (messages with no "id") seen
|
||||
// by this subprocess, so a follow-up Send can report the count back --
|
||||
// a notification itself gets no response to observe from the test side.
|
||||
var notificationsReceived atomic.Int64
|
||||
|
||||
func TestStdioTransportSetsSubprocessWorkingDirectory(t *testing.T) {
|
||||
workDir := t.TempDir()
|
||||
tr := helperTransportWithConfig(t, "normal", StdioTransportConfig{
|
||||
Dir: workDir,
|
||||
InitialBackoff: 10 * time.Millisecond,
|
||||
MaxBackoff: 50 * time.Millisecond,
|
||||
MaxRetries: 2,
|
||||
})
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tr.Stop(context.Background()) }()
|
||||
|
||||
response, err := tr.Send(context.Background(), []byte(`{"jsonrpc":"2.0","method":"ping","id":1}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var message struct {
|
||||
Result struct {
|
||||
CWD string `json:"cwd"`
|
||||
} `json:"result"`
|
||||
}
|
||||
if err := json.Unmarshal(response, &message); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if message.Result.CWD != workDir {
|
||||
t.Fatalf("MCP subprocess cwd = %q, want %q", message.Result.CWD, workDir)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Transport Tests ─────────────────────────────────────────────────────
|
||||
|
||||
// helperTransport creates a StdioTransport pointed at our test helper process.
|
||||
func helperTransport(t *testing.T, behavior string) *StdioTransport {
|
||||
t.Helper()
|
||||
return helperTransportWithConfig(t, behavior, StdioTransportConfig{
|
||||
InitialBackoff: 10 * time.Millisecond,
|
||||
MaxBackoff: 50 * time.Millisecond,
|
||||
MaxRetries: 2,
|
||||
})
|
||||
}
|
||||
|
||||
func helperTransportWithConfig(t *testing.T, behavior string, cfg StdioTransportConfig) *StdioTransport {
|
||||
t.Helper()
|
||||
if cfg.Command == "" {
|
||||
cfg.Command = os.Args[0]
|
||||
}
|
||||
if cfg.Args == nil {
|
||||
cfg.Args = []string{"-test.run=TestMCPServerHelper$"}
|
||||
}
|
||||
if cfg.Env == nil {
|
||||
cfg.Env = []string{
|
||||
"GO_WANT_MCP_HELPER=1",
|
||||
"MCP_HELPER_BEHAVIOR=" + behavior,
|
||||
}
|
||||
}
|
||||
// Set defaults if zero
|
||||
if cfg.InitialBackoff == 0 {
|
||||
cfg.InitialBackoff = 10 * time.Millisecond
|
||||
}
|
||||
if cfg.MaxBackoff == 0 {
|
||||
cfg.MaxBackoff = 50 * time.Millisecond
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
// nothing -- caller manages lifecycle
|
||||
})
|
||||
return NewStdioTransport(cfg)
|
||||
}
|
||||
|
||||
// ── Framing Tests ───────────────────────────────────────────────────────
|
||||
|
||||
func TestWriteMessage(t *testing.T) {
|
||||
t.Run("writes content-length header and body", func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
body := []byte(`{"key":"value"}`)
|
||||
if err := writeMessage(&buf, body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "{\"key\":\"value\"}\n"
|
||||
if got := buf.String(); got != want {
|
||||
t.Errorf("got %q, want %q", got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty body", func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
if err := writeMessage(&buf, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "\n"
|
||||
if got := buf.String(); got != want {
|
||||
t.Errorf("got %q, want %q", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestReadMessage(t *testing.T) {
|
||||
t.Run("reads newline-delimited JSON", func(t *testing.T) {
|
||||
input := "{\"ok\":true}\n"
|
||||
body, err := readMessage(strings.NewReader(input))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(body) != `{"ok":true}` {
|
||||
t.Errorf("got %q, want JSON body", string(body))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("accepts CRLF line ending", func(t *testing.T) {
|
||||
input := "{\"ok\":true}\r\n"
|
||||
body, err := readMessage(strings.NewReader(input))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(body) != `{"ok":true}` {
|
||||
t.Errorf("got %q, want JSON body", string(body))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("missing newline", func(t *testing.T) {
|
||||
_, err := readMessage(strings.NewReader(`{"ok":true}`))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for incomplete newline-delimited message")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("oversized message", func(t *testing.T) {
|
||||
input := strings.Repeat("x", maxMessageSize+1) + "\n"
|
||||
_, err := readMessage(strings.NewReader(input))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for oversized message")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("round-trip", func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
original := []byte(`{"jsonrpc":"2.0","id":1,"method":"ping"}`)
|
||||
if err := writeMessage(&buf, original); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, err := readMessage(&buf)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(body, original) {
|
||||
t.Errorf("got %q, want %q", string(body), string(original))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("truncated body returns error", func(t *testing.T) {
|
||||
input := `{"truncated":true}`
|
||||
_, err := readMessage(strings.NewReader(input))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for truncated body")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ── Transport Lifecycle Tests ───────────────────────────────────────────
|
||||
|
||||
func TestStdioTransportStartStop(t *testing.T) {
|
||||
tr := helperTransport(t, "normal")
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
if tr.State() != StateRunning {
|
||||
t.Errorf("state = %v, want Running", tr.State())
|
||||
}
|
||||
if err := tr.Stop(context.Background()); err != nil {
|
||||
t.Fatalf("Stop: %v", err)
|
||||
}
|
||||
if tr.State() != StateStopped {
|
||||
t.Errorf("state = %v, want Stopped", tr.State())
|
||||
}
|
||||
}
|
||||
|
||||
func TestStdioTransportDoubleStart(t *testing.T) {
|
||||
tr := helperTransport(t, "normal")
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err := tr.Start(context.Background())
|
||||
if err == nil {
|
||||
t.Error("expected error on double start")
|
||||
}
|
||||
_ = tr.Stop(context.Background())
|
||||
}
|
||||
|
||||
func TestStdioTransportStopWithoutStart(t *testing.T) {
|
||||
tr := helperTransport(t, "normal")
|
||||
// Stopping a never-started transport should succeed (idempotent).
|
||||
if err := tr.Stop(context.Background()); err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStdioTransportSendAndReceive(t *testing.T) {
|
||||
tr := helperTransport(t, "normal")
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tr.Stop(context.Background()) }()
|
||||
|
||||
resp, err := tr.Send(context.Background(), []byte(`{"jsonrpc":"2.0","method":"ping","id":1}`))
|
||||
if err != nil {
|
||||
t.Fatalf("Send: %v", err)
|
||||
}
|
||||
var msg Message
|
||||
if err := json.Unmarshal(resp, &msg); err != nil {
|
||||
t.Fatalf("unmarshal response: %v", err)
|
||||
}
|
||||
if msg.Error != nil {
|
||||
t.Fatalf("response error: %+v", msg.Error)
|
||||
}
|
||||
if string(msg.ID) != `1` {
|
||||
t.Errorf("response ID = %s, want 1", string(msg.ID))
|
||||
}
|
||||
}
|
||||
|
||||
func TestStdioTransportSendTimeout(t *testing.T) {
|
||||
tr := helperTransportWithConfig(t, "normal", StdioTransportConfig{
|
||||
InitialBackoff: 10 * time.Millisecond,
|
||||
MaxBackoff: 50 * time.Millisecond,
|
||||
MaxRetries: 2,
|
||||
SendTimeout: 1 * time.Millisecond,
|
||||
})
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tr.Stop(context.Background()) }()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
_, err := tr.Send(ctx, []byte(`{"jsonrpc":"2.0","method":"ping","id":1}`))
|
||||
if err != nil {
|
||||
t.Logf("Send error (expected due to short timeout): %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// blockingWriter never returns from Write until release is closed, letting
|
||||
// tests deterministically exercise writeMessageWithTimeout's timeout branch
|
||||
// without depending on OS pipe buffer sizes or subprocess scheduling.
|
||||
type blockingWriter struct {
|
||||
release <-chan struct{}
|
||||
}
|
||||
|
||||
func (b blockingWriter) Write(p []byte) (int, error) {
|
||||
<-b.release
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func TestWriteMessageWithTimeout(t *testing.T) {
|
||||
t.Run("zero timeout writes unbounded", func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
if err := writeMessageWithTimeout(&buf, []byte(`{}`), 0); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if buf.Len() == 0 {
|
||||
t.Fatal("expected data to be written")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("completes within timeout", func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
if err := writeMessageWithTimeout(&buf, []byte(`{}`), time.Second); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("times out on a blocked writer", func(t *testing.T) {
|
||||
release := make(chan struct{})
|
||||
defer close(release) // let the leaked write goroutine finish
|
||||
w := blockingWriter{release: release}
|
||||
err := writeMessageWithTimeout(w, []byte(`{}`), 10*time.Millisecond)
|
||||
if err == nil {
|
||||
t.Fatal("expected timeout error")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestStdioTransportRestartOnCrash(t *testing.T) {
|
||||
tr := helperTransport(t, "crash-after-init")
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// The subprocess should crash, and the transport should auto-restart.
|
||||
// We wait for the state to cycle back to Running.
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
var state TransportState
|
||||
for time.Now().Before(deadline) {
|
||||
state = tr.State()
|
||||
if state == StateRunning {
|
||||
break
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
if state != StateRunning {
|
||||
t.Fatalf("expected transport to restart to Running, got %v", state)
|
||||
}
|
||||
|
||||
_ = tr.Stop(context.Background())
|
||||
}
|
||||
|
||||
func TestStdioTransportMaxRetriesExceeded(t *testing.T) {
|
||||
// Use a behavior that immediately crashes after any message.
|
||||
tr := helperTransportWithConfig(t, "crash-after-init", StdioTransportConfig{
|
||||
InitialBackoff: 5 * time.Millisecond,
|
||||
MaxBackoff: 10 * time.Millisecond,
|
||||
MaxRetries: 3,
|
||||
})
|
||||
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// The process crashes immediately after init, transport tries to restart.
|
||||
// With MaxRetries=3 and very short backoffs, it should exceed retries quickly.
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
var state TransportState
|
||||
for time.Now().Before(deadline) {
|
||||
state = tr.State()
|
||||
if state == StateError {
|
||||
break
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
if state != StateError {
|
||||
t.Fatalf("expected StateError after max retries, got %v", state)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStdioTransportContextCancellation(t *testing.T) {
|
||||
tr := helperTransport(t, "normal")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel() // immediately cancelled
|
||||
|
||||
if err := tr.Start(ctx); err == nil {
|
||||
t.Error("expected error starting with cancelled context")
|
||||
}
|
||||
// State should remain stopped.
|
||||
if tr.State() != StateStopped {
|
||||
t.Errorf("state = %v, want Stopped", tr.State())
|
||||
}
|
||||
}
|
||||
|
||||
func TestStdioTransportConcurrentRequests(t *testing.T) {
|
||||
tr := helperTransport(t, "normal")
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tr.Stop(context.Background()) }()
|
||||
|
||||
const concurrency = 10
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, concurrency)
|
||||
|
||||
for i := range concurrency {
|
||||
wg.Add(1)
|
||||
go func(id int) {
|
||||
defer wg.Done()
|
||||
payload := fmt.Sprintf(`{"jsonrpc":"2.0","method":"ping","id":%d}`, id)
|
||||
resp, err := tr.Send(context.Background(), []byte(payload))
|
||||
if err != nil {
|
||||
errs <- fmt.Errorf("request %d: %w", id, err)
|
||||
return
|
||||
}
|
||||
var msg Message
|
||||
if err := json.Unmarshal(resp, &msg); err != nil {
|
||||
errs <- fmt.Errorf("request %d unmarshal: %w", id, err)
|
||||
return
|
||||
}
|
||||
if msg.Error != nil {
|
||||
errs <- fmt.Errorf("request %d error: %+v", id, msg.Error)
|
||||
return
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
|
||||
var allErr error
|
||||
for err := range errs {
|
||||
if allErr == nil {
|
||||
allErr = err
|
||||
} else {
|
||||
allErr = errors.Join(allErr, err)
|
||||
}
|
||||
}
|
||||
if allErr != nil {
|
||||
t.Fatal(allErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStdioTransportRestartAfterStop(t *testing.T) {
|
||||
tr := helperTransport(t, "normal")
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Stop the transport.
|
||||
if err := tr.Stop(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tr.State() != StateStopped {
|
||||
t.Errorf("state = %v, want Stopped", tr.State())
|
||||
}
|
||||
|
||||
// Restart it.
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Restart: %v", err)
|
||||
}
|
||||
if tr.State() != StateRunning {
|
||||
t.Errorf("state = %v, want Running", tr.State())
|
||||
}
|
||||
|
||||
// Should be able to send messages again.
|
||||
resp, err := tr.Send(context.Background(), []byte(`{"jsonrpc":"2.0","method":"ping","id":1}`))
|
||||
if err != nil {
|
||||
t.Fatalf("Send after restart: %v", err)
|
||||
}
|
||||
if len(resp) == 0 {
|
||||
t.Fatal("empty response after restart")
|
||||
}
|
||||
|
||||
_ = tr.Stop(context.Background())
|
||||
}
|
||||
|
||||
// TestStdioTransportConcurrentStartDuringStop is a regression test for a
|
||||
// race where Start() could see StateStopping (not guarded against) and spawn
|
||||
// a fresh subprocess while Stop() was still tearing down the previous one,
|
||||
// leaving the transport reporting a state inconsistent with what was
|
||||
// actually running. Start() now rejects StateStopping outright, so the
|
||||
// racing Start() must either fail cleanly or, if it loses the race entirely
|
||||
// and runs after Stop() finishes, succeed cleanly -- either way the final
|
||||
// state must be well-defined and self-consistent.
|
||||
func TestStdioTransportConcurrentStartDuringStop(t *testing.T) {
|
||||
tr := helperTransport(t, "normal")
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
var startErr error
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
startErr = tr.Start(context.Background())
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_ = tr.Stop(context.Background())
|
||||
}()
|
||||
wg.Wait()
|
||||
|
||||
state := tr.State()
|
||||
if state != StateStopped && state != StateRunning {
|
||||
t.Fatalf("state after concurrent Start/Stop = %v, want Stopped or Running", state)
|
||||
}
|
||||
t.Logf("concurrent Start error: %v, final state: %v", startErr, state)
|
||||
|
||||
_ = tr.Stop(context.Background())
|
||||
}
|
||||
|
||||
// TestStdioTransportCommitSpawnedProcessDiscardsWhenContextRacesAhead is a
|
||||
// regression test for a race where startSubprocess (the path Start() uses
|
||||
// to commit a freshly spawned subprocess) could clobber a StateStopped
|
||||
// already committed and reported by a concurrent Stop(): spawnProcess runs
|
||||
// without t.mu held (it's a real fork/exec), so Stop() can close t.stopCh and
|
||||
// return Stopped to its own caller while a spawn is still in flight. The
|
||||
// commit path used to unconditionally set state = StateRunning afterward,
|
||||
// wedging the transport in a Running state no caller of Stop() would ever
|
||||
// expect, with no way back to Stopped.
|
||||
//
|
||||
// The real race is timing-dependent, so this drives the two halves
|
||||
// (spawnProcess, then commitSpawnedProcess) directly and in order
|
||||
// (white-box, same package) to deterministically simulate a Stop() landing
|
||||
// in between them: the process is actually spawned and running (so the
|
||||
// commit path's kill/reap of a live process is genuinely exercised), then
|
||||
// the context is cancelled to simulate Stop() winning the race, then commit
|
||||
// runs and must discard rather than clobber.
|
||||
func TestStdioTransportCommitSpawnedProcessDiscardsWhenContextRacesAhead(t *testing.T) {
|
||||
tr := NewStdioTransport(StdioTransportConfig{
|
||||
Command: os.Args[0],
|
||||
Args: []string{"-test.run=TestMCPServerHelper$"},
|
||||
Env: []string{"GO_WANT_MCP_HELPER=1", "MCP_HELPER_BEHAVIOR=normal"},
|
||||
})
|
||||
|
||||
tr.mu.Lock()
|
||||
tr.state = StateStarting
|
||||
tr.stopCh = make(chan struct{})
|
||||
tr.mu.Unlock()
|
||||
|
||||
cmd, stdin, stdout, err := tr.spawnProcess(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("spawnProcess: %v", err)
|
||||
}
|
||||
|
||||
// Simulate a concurrent Stop() winning the race between spawn and
|
||||
// commit: it would have closed this exact stop channel.
|
||||
tr.mu.Lock()
|
||||
close(tr.stopCh)
|
||||
tr.mu.Unlock()
|
||||
|
||||
err = tr.commitSpawnedProcess(context.Background(), cmd, stdin, stdout, false)
|
||||
if err == nil {
|
||||
t.Fatal("expected error when context was cancelled before commit")
|
||||
}
|
||||
if tr.State() != StateStopped {
|
||||
t.Fatalf("state = %v, want Stopped", tr.State())
|
||||
}
|
||||
|
||||
tr.mu.Lock()
|
||||
gotCmd := tr.cmd
|
||||
tr.mu.Unlock()
|
||||
if gotCmd != nil {
|
||||
t.Fatal("expected no committed subprocess after discard")
|
||||
}
|
||||
}
|
||||
|
||||
// ── Error State Tests ───────────────────────────────────────────────────
|
||||
|
||||
func TestStdioTransportRestartFromError(t *testing.T) {
|
||||
tr := helperTransportWithConfig(t, "crash-after-init", StdioTransportConfig{
|
||||
InitialBackoff: 5 * time.Millisecond,
|
||||
MaxBackoff: 10 * time.Millisecond,
|
||||
MaxRetries: 2,
|
||||
})
|
||||
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Wait for it to enter Error state.
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if tr.State() == StateError {
|
||||
break
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
if tr.State() != StateError {
|
||||
t.Fatalf("expected Error state, got %v", tr.State())
|
||||
}
|
||||
|
||||
// Now use a fresh cmd by restarting. Since the behavior is still "crash-after-init",
|
||||
// it'll crash again. But we're testing that Restart (via Start) transitions from Error.
|
||||
// We accept either Running or Error (depending on timing).
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
// Starting a crashing process may return nil if the retry loop starts in background.
|
||||
// That's fine -- we just check the transition happened.
|
||||
t.Logf("Start from Error: %v (acceptable)", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStdioTransportStateTransitions(t *testing.T) {
|
||||
t.Run("initial state is stopped", func(t *testing.T) {
|
||||
tr := NewStdioTransport(StdioTransportConfig{
|
||||
Command: os.Args[0],
|
||||
})
|
||||
if tr.State() != StateStopped {
|
||||
t.Errorf("initial state = %v, want Stopped", tr.State())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("config validation rejects empty command", func(t *testing.T) {
|
||||
tr := NewStdioTransport(StdioTransportConfig{})
|
||||
if err := tr.Start(context.Background()); err == nil {
|
||||
t.Error("expected error for empty command")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ── Send Error Handling ─────────────────────────────────────────────────
|
||||
|
||||
func TestStdioTransportSendAfterStop(t *testing.T) {
|
||||
tr := helperTransport(t, "normal")
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tr.Stop(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, err := tr.Send(context.Background(), []byte(`{"jsonrpc":"2.0","method":"ping","id":1}`))
|
||||
if err == nil {
|
||||
t.Error("expected error sending after stop")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStdioTransportNotify(t *testing.T) {
|
||||
tr := helperTransport(t, "normal")
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tr.Stop(context.Background()) }()
|
||||
|
||||
if err := tr.Notify(context.Background(), []byte(`{"jsonrpc":"2.0","method":"notifications/test"}`)); err != nil {
|
||||
t.Fatalf("Notify: %v", err)
|
||||
}
|
||||
|
||||
// A follow-up Send (which DOES get a response) reports how many
|
||||
// notifications the subprocess has seen, proving Notify's write
|
||||
// actually reached the server without Notify itself blocking for a
|
||||
// reply (it has none to wait for).
|
||||
resp, err := tr.Send(context.Background(), []byte(`{"jsonrpc":"2.0","method":"ping","id":1}`))
|
||||
if err != nil {
|
||||
t.Fatalf("Send: %v", err)
|
||||
}
|
||||
var msg Message
|
||||
if err := json.Unmarshal(resp, &msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var result struct {
|
||||
NotificationsReceived int64 `json:"notifications_received"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Result, &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.NotificationsReceived < 1 {
|
||||
t.Fatalf("subprocess reports %d notifications received, want >= 1", result.NotificationsReceived)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStdioTransportNotifyBeforeStartReturnsError(t *testing.T) {
|
||||
tr := helperTransport(t, "normal")
|
||||
err := tr.Notify(context.Background(), []byte(`{"jsonrpc":"2.0","method":"notifications/test"}`))
|
||||
if err == nil {
|
||||
t.Fatal("expected error notifying a transport that was never started")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStdioTransportNotifyAfterStopReturnsError(t *testing.T) {
|
||||
tr := helperTransport(t, "normal")
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tr.Stop(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err := tr.Notify(context.Background(), []byte(`{"jsonrpc":"2.0","method":"notifications/test"}`))
|
||||
if err == nil {
|
||||
t.Fatal("expected error notifying a stopped transport")
|
||||
}
|
||||
}
|
||||
|
||||
// ── Additional server-behavior and error-path coverage ─────────────────
|
||||
|
||||
// TestStdioTransportSendContextCancellationWhileWaiting exercises the
|
||||
// ctx.Done() branch in Send: a server that answers "initialize" once and
|
||||
// then goes silent forever, so a follow-up Send can only be resolved by the
|
||||
// caller's context deadline, not by a subprocess response.
|
||||
func TestStdioTransportSendContextCancellationWhileWaiting(t *testing.T) {
|
||||
tr := helperTransport(t, "hang-on-start")
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tr.Stop(context.Background()) }()
|
||||
|
||||
if _, err := tr.Send(context.Background(), []byte(`{"jsonrpc":"2.0","method":"initialize","id":1}`)); err != nil {
|
||||
t.Fatalf("initialize: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
_, err := tr.Send(ctx, []byte(`{"jsonrpc":"2.0","method":"never-answered","id":2}`))
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("got %v, want context.DeadlineExceeded", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStdioTransportBadFraming exercises the reader's malformed-framing
|
||||
// path against a real, live subprocess (rather than a synthetic
|
||||
// strings.Reader as in TestReadMessage): the server writes a response with
|
||||
// no trailing newline, which readMessage cannot parse, so the reader
|
||||
// goroutine treats the transport as dead and fails pending requests.
|
||||
func TestStdioTransportBadFraming(t *testing.T) {
|
||||
tr := helperTransportWithConfig(t, "bad-framing", StdioTransportConfig{
|
||||
InitialBackoff: 10 * time.Millisecond,
|
||||
MaxBackoff: 50 * time.Millisecond,
|
||||
MaxRetries: 1,
|
||||
})
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tr.Stop(context.Background()) }()
|
||||
|
||||
_, err := tr.Send(context.Background(), []byte(`{"jsonrpc":"2.0","method":"ping","id":1}`))
|
||||
if err == nil {
|
||||
t.Fatal("expected error: malformed response framing should fail the pending request")
|
||||
}
|
||||
}
|
||||
|
||||
// TestStdioTransportSendUnparsableID exercises extractMessageID's error
|
||||
// branch as reached through Send, which must reject the body before ever
|
||||
// touching the subprocess.
|
||||
func TestStdioTransportSendUnparsableID(t *testing.T) {
|
||||
tr := helperTransport(t, "normal")
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tr.Stop(context.Background()) }()
|
||||
|
||||
_, err := tr.Send(context.Background(), []byte(`not json`))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for unparsable message id")
|
||||
}
|
||||
}
|
||||
|
||||
// TestStdioTransportSendWriteFailureCleansPending exercises Send's
|
||||
// write-failure cleanup branch by closing the subprocess's stdin out from
|
||||
// under it directly (same package, so the unexported field is reachable),
|
||||
// simulating a pipe that breaks mid-write.
|
||||
func TestStdioTransportSendWriteFailureCleansPending(t *testing.T) {
|
||||
tr := helperTransport(t, "normal")
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tr.Stop(context.Background()) }()
|
||||
|
||||
tr.mu.Lock()
|
||||
stdin := tr.stdin
|
||||
tr.mu.Unlock()
|
||||
if err := stdin.Close(); err != nil {
|
||||
t.Fatalf("close stdin: %v", err)
|
||||
}
|
||||
|
||||
_, err := tr.Send(context.Background(), []byte(`{"jsonrpc":"2.0","method":"ping","id":1}`))
|
||||
if err == nil {
|
||||
t.Fatal("expected write error after stdin closed")
|
||||
}
|
||||
|
||||
tr.mu.Lock()
|
||||
_, stillPending := tr.pending["1"]
|
||||
tr.mu.Unlock()
|
||||
if stillPending {
|
||||
t.Fatal("pending entry was not cleaned up after write failure")
|
||||
}
|
||||
}
|
||||
|
||||
// ── Framing edge cases ──────────────────────────────────────────────────
|
||||
|
||||
func TestFramingCarriageReturnOnly(t *testing.T) {
|
||||
input := "body\r\n"
|
||||
body, err := readMessage(strings.NewReader(input))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if string(body) != "body" {
|
||||
t.Errorf("got %q, want %q", string(body), "body")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFramingMultipleMessages(t *testing.T) {
|
||||
input := "hello\nbye\n"
|
||||
br := bufio.NewReader(strings.NewReader(input))
|
||||
body1, err := readMessage(br)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(body1) != "hello" {
|
||||
t.Errorf("first: got %q, want %q", string(body1), "hello")
|
||||
}
|
||||
body2, err := readMessage(br)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(body2) != "bye" {
|
||||
t.Errorf("second: got %q, want %q", string(body2), "bye")
|
||||
}
|
||||
}
|
||||
@@ -1,231 +0,0 @@
|
||||
package minimax
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// fakeAPI serves a MiniMax API double. create answers with taskID (or
|
||||
// createStatus/createBody when set); each call to query pops the next
|
||||
// entry from queryResponses, repeating the last one once exhausted.
|
||||
type fakeAPI struct {
|
||||
t *testing.T
|
||||
createStatus int
|
||||
createBody string
|
||||
taskID string
|
||||
queryResponses []string
|
||||
queryCalls int
|
||||
lastAuth string
|
||||
lastCreateBody map[string]any
|
||||
}
|
||||
|
||||
func (f *fakeAPI) server() *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
f.lastAuth = r.Header.Get("Authorization")
|
||||
switch {
|
||||
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/v2/video_generation"):
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
f.t.Fatalf("decode create body: %v", err)
|
||||
}
|
||||
f.lastCreateBody = body
|
||||
|
||||
if f.createStatus != 0 && f.createStatus != http.StatusOK {
|
||||
w.WriteHeader(f.createStatus)
|
||||
_, _ = w.Write([]byte(f.createBody))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"task_id":"` + f.taskID + `"}`))
|
||||
|
||||
case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/v2/query/video_generation/"):
|
||||
idx := f.queryCalls
|
||||
if idx >= len(f.queryResponses) {
|
||||
idx = len(f.queryResponses) - 1
|
||||
}
|
||||
f.queryCalls++
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(f.queryResponses[idx]))
|
||||
|
||||
default:
|
||||
f.t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
func newTestClient(t *testing.T, api *fakeAPI, pollInterval time.Duration) *Client {
|
||||
t.Helper()
|
||||
srv := api.server()
|
||||
t.Cleanup(srv.Close)
|
||||
var slept []time.Duration
|
||||
return New(Config{
|
||||
Enabled: true,
|
||||
APIKey: "test-key",
|
||||
BaseURL: srv.URL,
|
||||
Timeout: 5 * time.Second,
|
||||
PollInterval: pollInterval,
|
||||
// Large relative to any pollInterval used in these tests (including
|
||||
// the 5s default when pollInterval is 0): Sleep is faked, so this
|
||||
// costs nothing in real time and just has to outlast however many
|
||||
// polls a test's queryResponses table needs.
|
||||
MaxWait: 24 * time.Hour,
|
||||
Sleep: func(d time.Duration) { slept = append(slept, d) },
|
||||
})
|
||||
}
|
||||
|
||||
// A submitted job must carry the bearer key and the prompt, and once
|
||||
// MiniMax reports success the client must hand back the hosted URL, not
|
||||
// just the fact that it succeeded.
|
||||
func TestGenerateAndWaitReturnsURLOnSuccess(t *testing.T) {
|
||||
api := &fakeAPI{t: t, taskID: "task-1", queryResponses: []string{
|
||||
`{"task":{"id":"task-1","status":"succeeded","content":{"url":"https://cdn.example.com/v.mp4"}}}`,
|
||||
}}
|
||||
client := newTestClient(t, api, 0)
|
||||
|
||||
url, err := client.GenerateAndWait(context.Background(), GenerateRequest{Prompt: "a cat on a skateboard"})
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateAndWait: %v", err)
|
||||
}
|
||||
if url != "https://cdn.example.com/v.mp4" {
|
||||
t.Errorf("url = %q, want the succeeded task's content url", url)
|
||||
}
|
||||
if api.lastAuth != "Bearer test-key" {
|
||||
t.Errorf("Authorization = %q, want Bearer test-key", api.lastAuth)
|
||||
}
|
||||
if api.lastCreateBody["content"] == nil {
|
||||
t.Fatal("create body carried no content")
|
||||
}
|
||||
}
|
||||
|
||||
// A job that starts queued and moves through running before succeeding
|
||||
// must be polled repeatedly, not just once.
|
||||
func TestGenerateAndWaitPollsUntilTerminal(t *testing.T) {
|
||||
api := &fakeAPI{t: t, taskID: "task-1", queryResponses: []string{
|
||||
`{"task":{"id":"task-1","status":"queued"}}`,
|
||||
`{"task":{"id":"task-1","status":"running"}}`,
|
||||
`{"task":{"id":"task-1","status":"succeeded","content":{"url":"https://cdn.example.com/v.mp4"}}}`,
|
||||
}}
|
||||
client := newTestClient(t, api, 0)
|
||||
|
||||
url, err := client.GenerateAndWait(context.Background(), GenerateRequest{Prompt: "a cat on a skateboard"})
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateAndWait: %v", err)
|
||||
}
|
||||
if url != "https://cdn.example.com/v.mp4" {
|
||||
t.Errorf("url = %q", url)
|
||||
}
|
||||
if api.queryCalls != 3 {
|
||||
t.Errorf("query calls = %d, want 3 (queued, running, succeeded)", api.queryCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// A failed generation must surface the platform's own error message, not
|
||||
// just "it failed" -- the model needs enough detail to tell the user
|
||||
// something useful about why.
|
||||
func TestGenerateAndWaitReturnsErrorOnFailedStatus(t *testing.T) {
|
||||
api := &fakeAPI{t: t, taskID: "task-1", queryResponses: []string{
|
||||
`{"task":{"id":"task-1","status":"failed","error":{"code":"content_policy","message":"prompt rejected"}}}`,
|
||||
}}
|
||||
client := newTestClient(t, api, 0)
|
||||
|
||||
_, err := client.GenerateAndWait(context.Background(), GenerateRequest{Prompt: "a cat on a skateboard"})
|
||||
if err == nil {
|
||||
t.Fatal("expected an error for a failed task")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "prompt rejected") {
|
||||
t.Errorf("error = %v, want it to contain the platform's message", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A create call that MiniMax itself rejects (bad request, auth, quota,
|
||||
// content policy, rate limit) must fail before any polling starts, with
|
||||
// the platform's own description rather than a generic HTTP error.
|
||||
func TestGenerateReportsCreateFailures(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
wantSubstr string
|
||||
}{
|
||||
{
|
||||
name: "auth",
|
||||
status: http.StatusUnauthorized,
|
||||
body: `{"type":"error","error":{"type":"auth_error","message":"invalid API key","http_code":"401"},"request_id":"r1"}`,
|
||||
wantSubstr: "invalid API key",
|
||||
},
|
||||
{
|
||||
name: "insufficient balance",
|
||||
status: http.StatusPaymentRequired,
|
||||
body: `{"type":"error","error":{"type":"balance_error","message":"insufficient balance","http_code":"402"},"request_id":"r2"}`,
|
||||
wantSubstr: "insufficient balance",
|
||||
},
|
||||
{
|
||||
name: "rate limited",
|
||||
status: http.StatusTooManyRequests,
|
||||
body: `{"type":"error","error":{"type":"rate_limit","message":"too many requests","http_code":"429"},"request_id":"r3"}`,
|
||||
wantSubstr: "too many requests",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
api := &fakeAPI{t: t, createStatus: tt.status, createBody: tt.body}
|
||||
client := newTestClient(t, api, 0)
|
||||
|
||||
_, err := client.GenerateAndWait(context.Background(), GenerateRequest{Prompt: "a cat"})
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.wantSubstr) {
|
||||
t.Errorf("error = %v, want it to contain %q", err, tt.wantSubstr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A job that never reaches a terminal status must not poll forever: it has
|
||||
// to give up once MaxWait elapses and say so, rather than hanging the tool
|
||||
// call (and the whole turn) indefinitely.
|
||||
func TestGenerateAndWaitTimesOutWithoutRealSleep(t *testing.T) {
|
||||
responses := make([]string, 100)
|
||||
for i := range responses {
|
||||
responses[i] = `{"task":{"id":"task-1","status":"running"}}`
|
||||
}
|
||||
api := &fakeAPI{t: t, taskID: "task-1", queryResponses: responses}
|
||||
|
||||
srv := api.server()
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
elapsed := time.Duration(0)
|
||||
client := New(Config{
|
||||
Enabled: true,
|
||||
APIKey: "test-key",
|
||||
BaseURL: srv.URL,
|
||||
Timeout: 5 * time.Second,
|
||||
PollInterval: time.Second,
|
||||
MaxWait: 10 * time.Second,
|
||||
Sleep: func(d time.Duration) { elapsed += d },
|
||||
})
|
||||
|
||||
start := time.Now()
|
||||
_, err := client.GenerateAndWait(context.Background(), GenerateRequest{Prompt: "a cat"})
|
||||
wallClock := time.Since(start)
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("expected a timeout error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "timed out") {
|
||||
t.Errorf("error = %v, want a timeout error", err)
|
||||
}
|
||||
if wallClock > time.Second {
|
||||
t.Fatalf("test took %v of real wall-clock time; Sleep was not honored as the delay source", wallClock)
|
||||
}
|
||||
if elapsed < 10*time.Second {
|
||||
t.Errorf("simulated elapsed = %v, want at least MaxWait (10s)", elapsed)
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
package minimax
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// Disabled must withdraw the tool entirely: an advertised tool that always
|
||||
// fails costs the model a wasted round trip to discover it doesn't work,
|
||||
// the same reasoning webfetch.Tool documents for its own Enabled check.
|
||||
func TestToolReturnsNilWhenDisabled(t *testing.T) {
|
||||
if entry := Tool(Config{Enabled: false}); entry != nil {
|
||||
t.Fatal("expected a nil entry when disabled")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolHasRequiredPromptSchema(t *testing.T) {
|
||||
entry := Tool(Config{Enabled: true, APIKey: "k"})
|
||||
if entry == nil {
|
||||
t.Fatal("expected a non-nil entry")
|
||||
}
|
||||
if entry.Name != ToolName {
|
||||
t.Errorf("Name = %q, want %q", entry.Name, ToolName)
|
||||
}
|
||||
required, _ := entry.Schema["required"].([]any)
|
||||
if len(required) != 1 || required[0] != "prompt" {
|
||||
t.Errorf("required = %v, want [prompt]", required)
|
||||
}
|
||||
}
|
||||
|
||||
// A missing prompt must be rejected before any network call, matching
|
||||
// webfetch's own required-field check.
|
||||
func TestToolHandlerRejectsEmptyPrompt(t *testing.T) {
|
||||
entry := Tool(Config{Enabled: true, APIKey: "k"})
|
||||
if _, err := entry.Handler(context.Background(), map[string]any{}); err == nil {
|
||||
t.Fatal("expected an error for a missing prompt")
|
||||
}
|
||||
}
|
||||
|
||||
// The handler's success path must produce a tools.MultimodalResult carrying
|
||||
// the video as a URLs entry: that is the shared envelope the gateway wiring
|
||||
// (cmd/archied) knows how to turn into a delivered attachment. Returning a
|
||||
// bare string here would leave the video undeliverable no matter how good
|
||||
// the rest of the pipeline is.
|
||||
func TestToolHandlerReturnsMultimodalResultOnSuccess(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
_, _ = w.Write([]byte(`{"task_id":"task-1"}`))
|
||||
default:
|
||||
_, _ = w.Write([]byte(`{"task":{"id":"task-1","status":"succeeded","content":{"url":"https://cdn.example.com/v.mp4"}}}`))
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
entry := Tool(Config{
|
||||
Enabled: true,
|
||||
APIKey: "k",
|
||||
BaseURL: srv.URL,
|
||||
Timeout: 5 * time.Second,
|
||||
PollInterval: 0,
|
||||
MaxWait: time.Hour,
|
||||
Sleep: func(time.Duration) {},
|
||||
})
|
||||
|
||||
out, err := entry.Handler(context.Background(), map[string]any{"prompt": "a cat on a skateboard"})
|
||||
if err != nil {
|
||||
t.Fatalf("Handler: %v", err)
|
||||
}
|
||||
|
||||
data, err := json.Marshal(out)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal handler output: %v", err)
|
||||
}
|
||||
var result tools.MultimodalResult
|
||||
if err := json.Unmarshal(data, &result); err != nil {
|
||||
t.Fatalf("handler output is not a MultimodalResult: %v", err)
|
||||
}
|
||||
if !result.IsMultimodal {
|
||||
t.Error("expected IsMultimodal = true")
|
||||
}
|
||||
if len(result.URLs) != 1 || result.URLs[0].Type != "video" || result.URLs[0].URL != "https://cdn.example.com/v.mp4" {
|
||||
t.Errorf("URLs = %+v, want [{video https://cdn.example.com/v.mp4}]", result.URLs)
|
||||
}
|
||||
}
|
||||
|
||||
// A generation failure must surface as a handler error, not a
|
||||
// MultimodalResult with no URLs: a silently empty result reads to the
|
||||
// model as "it worked but produced nothing" rather than "it failed."
|
||||
func TestToolHandlerReturnsErrorOnGenerationFailure(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
_, _ = w.Write([]byte(`{"task_id":"task-1"}`))
|
||||
default:
|
||||
_, _ = w.Write([]byte(`{"task":{"id":"task-1","status":"failed","error":{"message":"prompt rejected"}}}`))
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
entry := Tool(Config{
|
||||
Enabled: true,
|
||||
APIKey: "k",
|
||||
BaseURL: srv.URL,
|
||||
Timeout: 5 * time.Second,
|
||||
PollInterval: 0,
|
||||
MaxWait: time.Hour,
|
||||
Sleep: func(time.Duration) {},
|
||||
})
|
||||
|
||||
if _, err := entry.Handler(context.Background(), map[string]any{"prompt": "a cat"}); err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMultimodalResultJSONFields(t *testing.T) {
|
||||
r := MultimodalResult{
|
||||
IsMultimodal: true,
|
||||
Summary: "generated a chart",
|
||||
SubdirHint: "tool-output/chart_generator",
|
||||
Files: []string{"tool-output/chart_generator/0.png"},
|
||||
}
|
||||
data, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got map[string]any
|
||||
if err := json.Unmarshal(data, &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got["is_multimodal"] != true {
|
||||
t.Errorf("is_multimodal = %v, want true", got["is_multimodal"])
|
||||
}
|
||||
if got["summary"] != "generated a chart" {
|
||||
t.Errorf("summary = %v", got["summary"])
|
||||
}
|
||||
if got["subdir_hint"] != "tool-output/chart_generator" {
|
||||
t.Errorf("subdir_hint = %v", got["subdir_hint"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultimodalResultOmitsEmptyOptionalFields(t *testing.T) {
|
||||
r := MultimodalResult{IsMultimodal: true, Summary: "no media dir configured"}
|
||||
data, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got map[string]any
|
||||
if err := json.Unmarshal(data, &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := got["subdir_hint"]; ok {
|
||||
t.Error("subdir_hint should be omitted when empty")
|
||||
}
|
||||
if _, ok := got["files"]; ok {
|
||||
t.Error("files should be omitted when empty")
|
||||
}
|
||||
if _, ok := got["urls"]; ok {
|
||||
t.Error("urls should be omitted when empty")
|
||||
}
|
||||
}
|
||||
|
||||
// A tool whose media lives at a remote URL (a generation API's hosted
|
||||
// result) rather than local bytes has nowhere to put it in Files, which is
|
||||
// always a path under SubdirHint. URLs is that case.
|
||||
func TestMultimodalResultURLsRoundTrip(t *testing.T) {
|
||||
r := MultimodalResult{
|
||||
IsMultimodal: true,
|
||||
Summary: "generated a video",
|
||||
URLs: []MediaRef{{Type: "video", URL: "https://example.com/v.mp4"}},
|
||||
}
|
||||
data, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got MultimodalResult
|
||||
if err := json.Unmarshal(data, &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.URLs) != 1 || got.URLs[0].Type != "video" || got.URLs[0].URL != "https://example.com/v.mp4" {
|
||||
t.Errorf("URLs round-trip = %+v, want [{video https://example.com/v.mp4}]", got.URLs)
|
||||
}
|
||||
}
|
||||
@@ -1,259 +0,0 @@
|
||||
package builtin_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
provider "github.com/samcharles93/archie-core/internal/tools/provider/builtin"
|
||||
)
|
||||
|
||||
func startedProvider(t *testing.T, workspace string) *provider.Provider {
|
||||
t.Helper()
|
||||
p := provider.New(workspace, false)
|
||||
if err := p.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Stop(context.Background()) })
|
||||
return p
|
||||
}
|
||||
|
||||
func TestDiscoverExposesWorkspaceTools(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
entries, err := startedProvider(t, t.TempDir()).Discover(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Discover: %v", err)
|
||||
}
|
||||
|
||||
got := make(map[string]bool, len(entries))
|
||||
for _, e := range entries {
|
||||
got[e.Name] = true
|
||||
if e.Handler == nil {
|
||||
t.Errorf("tool %q has no handler, so the model could call something that does nothing", e.Name)
|
||||
}
|
||||
if e.Description == "" {
|
||||
t.Errorf("tool %q has no description", e.Name)
|
||||
}
|
||||
}
|
||||
for _, want := range []string{"read", "write", "edit", "shell", "grep", "find"} {
|
||||
if !got[want] {
|
||||
t.Errorf("tool %q missing from discovery; got %v", want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandlerRoundTripsThroughTauExecutor covers the seam this package
|
||||
// exists for: archie hands the handler decoded arguments, tau's executor
|
||||
// wants raw JSON, and the result comes back as content.
|
||||
func TestHandlerRoundTripsThroughTauExecutor(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "hello.txt"), []byte("g'day\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
entries, err := startedProvider(t, dir).Discover(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Discover: %v", err)
|
||||
}
|
||||
var read func(context.Context, map[string]any) (any, error)
|
||||
for _, e := range entries {
|
||||
if e.Name == "read" {
|
||||
read = e.Handler
|
||||
}
|
||||
}
|
||||
if read == nil {
|
||||
t.Fatal("no read tool discovered")
|
||||
}
|
||||
|
||||
out, err := read(context.Background(), map[string]any{"path": "hello.txt"})
|
||||
if err != nil {
|
||||
t.Fatalf("read handler: %v", err)
|
||||
}
|
||||
if text, ok := out.(string); !ok || !strings.Contains(text, "g'day") {
|
||||
t.Errorf("read returned %#v, want content containing the file text", out)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandlerSurfacesToolFailureAsError guards the second half of the seam:
|
||||
// tau reports a tool-level failure in Result.IsError rather than as an
|
||||
// error, and swallowing that would show the model a successful call.
|
||||
func TestHandlerSurfacesToolFailureAsError(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
entries, err := startedProvider(t, t.TempDir()).Discover(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Discover: %v", err)
|
||||
}
|
||||
for _, e := range entries {
|
||||
if e.Name != "read" {
|
||||
continue
|
||||
}
|
||||
if _, err := e.Handler(context.Background(), map[string]any{"path": "absent.txt"}); err == nil {
|
||||
t.Error("reading a missing file reported success")
|
||||
}
|
||||
return
|
||||
}
|
||||
t.Fatal("no read tool discovered")
|
||||
}
|
||||
|
||||
// TestShellHandlerEnforcesHardlineRules checks the rules are actually
|
||||
// wired into the executing handler. The rules are tested in
|
||||
// internal/tools/command; what matters here is that a call cannot reach
|
||||
// tau's executor without passing through them.
|
||||
func TestShellHandlerEnforcesHardlineRules(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
shell := shellHandler(t, t.TempDir())
|
||||
|
||||
if _, err := shell(context.Background(), map[string]any{"command": "rm -rf /"}); err == nil {
|
||||
t.Error("the shell tool accepted a recursive delete of /")
|
||||
} else if !strings.Contains(err.Error(), "refused") {
|
||||
t.Errorf("error = %v, want a refusal naming the rule", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestShellHandlerAllowsOrdinaryCommands guards the other direction: the
|
||||
// screen must not stand between the model and normal work.
|
||||
func TestShellHandlerAllowsOrdinaryCommands(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
out, err := shellHandler(t, dir)(context.Background(), map[string]any{
|
||||
"command": `echo "rm -rf / is only mentioned here"`,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("an ordinary echo was refused: %v", err)
|
||||
}
|
||||
if text, ok := out.(string); !ok || !strings.Contains(text, "only mentioned here") {
|
||||
t.Errorf("shell returned %#v, want the echoed text", out)
|
||||
}
|
||||
}
|
||||
|
||||
func shellHandler(t *testing.T, workspace string) func(context.Context, map[string]any) (any, error) {
|
||||
t.Helper()
|
||||
|
||||
entries, err := startedProvider(t, workspace).Discover(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Discover: %v", err)
|
||||
}
|
||||
for _, e := range entries {
|
||||
if e.Name == "shell" {
|
||||
return e.Handler
|
||||
}
|
||||
}
|
||||
t.Fatal("no shell tool discovered")
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestUnconfiguredWorkspaceIsRejected keeps the tools from silently rooting
|
||||
// at the daemon's own working directory, which in the container is /.
|
||||
func TestUnconfiguredWorkspaceIsRejected(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if err := provider.New("", false).Start(context.Background()); err == nil {
|
||||
t.Error("a provider with no workspace started successfully")
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnrestrictedFilesystemReachesOutsideWorkspace covers the operator
|
||||
// posture end to end, through a real read of a real file.
|
||||
//
|
||||
// A deployment whose agent partitions disks, mounts them and migrates data is
|
||||
// working across the filesystem by definition. Confined, every one of those
|
||||
// touches has to go through shell -- which was never confined anyway -- so the
|
||||
// jail only ever decided which tool did the work, not what the agent reached.
|
||||
//
|
||||
// Not parallel: confinement is process-wide, so these two subtests must not
|
||||
// run beside tests that assume the default.
|
||||
func TestUnrestrictedFilesystemReachesOutsideWorkspace(t *testing.T) {
|
||||
// A file deliberately outside the workspace, as /etc or a fresh mount
|
||||
// would be.
|
||||
outside := filepath.Join(t.TempDir(), "fstab")
|
||||
if err := os.WriteFile(outside, []byte("UUID=1234 /mnt/newdisk ext4 defaults 0 2\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
unrestricted bool
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "confined refuses", unrestricted: false, wantErr: true},
|
||||
{name: "unrestricted reads", unrestricted: true},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
p := provider.New(t.TempDir(), tc.unrestricted)
|
||||
if err := p.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Stop(context.Background()) })
|
||||
|
||||
entries, err := p.Discover(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var read func(context.Context, map[string]any) (any, error)
|
||||
for _, e := range entries {
|
||||
if e.Name == "read" {
|
||||
read = e.Handler
|
||||
}
|
||||
}
|
||||
if read == nil {
|
||||
t.Fatal("no read tool discovered")
|
||||
}
|
||||
|
||||
out, err := read(context.Background(), map[string]any{"path": outside})
|
||||
if tc.wantErr {
|
||||
if err == nil {
|
||||
t.Fatal("read reached outside the workspace while confined")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("read was refused with confinement disabled: %v", err)
|
||||
}
|
||||
if text, ok := out.(string); !ok || !strings.Contains(text, "/mnt/newdisk") {
|
||||
t.Errorf("read returned %#v, want the file contents", out)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Leave the process as we found it for any test that runs after.
|
||||
t.Cleanup(func() {
|
||||
p := provider.New(t.TempDir(), false)
|
||||
_ = p.Start(context.Background())
|
||||
_ = p.Stop(context.Background())
|
||||
})
|
||||
}
|
||||
|
||||
// TestWorkspaceToolsCarryTheirOwnIcon pins that each builtin declares an icon
|
||||
// and that the conversion carries it. A chat surface renders what the tool
|
||||
// registered, so an icon missing here is an icon missing on screen.
|
||||
func TestWorkspaceToolsCarryTheirOwnIcon(t *testing.T) {
|
||||
p := startedProvider(t, t.TempDir())
|
||||
entries, err := p.Discover(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("Tools: %v", err)
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
t.Fatal("no workspace tools registered")
|
||||
}
|
||||
seen := make(map[string]bool)
|
||||
for _, entry := range entries {
|
||||
if entry.Emoji == "" {
|
||||
t.Errorf("tool %q registered no icon", entry.Name)
|
||||
continue
|
||||
}
|
||||
seen[entry.Emoji] = true
|
||||
}
|
||||
if len(seen) < 2 {
|
||||
t.Errorf("icons = %v, want tools to be distinguishable by icon", seen)
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
package provider_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestToolProviderEngineContractExists(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
source, err := os.ReadFile("provider.go")
|
||||
if err != nil {
|
||||
t.Fatalf("read provider.go: %v", err)
|
||||
}
|
||||
text := string(source)
|
||||
for _, required := range []string{
|
||||
"type Engine interface",
|
||||
"plugin.Module",
|
||||
"Discover(context.Context) ([]tools.ToolEntry, error)",
|
||||
"type Registry struct",
|
||||
"func (r *Registry) Register(engine Engine) error",
|
||||
"func (r *Registry) Get(id string) (Engine, bool)",
|
||||
} {
|
||||
if !strings.Contains(text, required) {
|
||||
t.Errorf("provider.go does not contain required typed-family contract %q", required)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestArchiedWiresTypedProvidersAndExecutableConsumers(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mainPath := filepath.Join("..", "..", "..", "internal", "app", "archied", "main.go")
|
||||
source, err := os.ReadFile(mainPath)
|
||||
if err != nil {
|
||||
t.Fatalf("read archied main: %v", err)
|
||||
}
|
||||
var text strings.Builder
|
||||
text.WriteString(string(source))
|
||||
|
||||
// Also check the chat composition files, which hold the chat-turn wiring
|
||||
// extracted from main.go during the structural refactor.
|
||||
for _, name := range []string{"telegram_setup.go", "chat_turn_model.go", "bootstrap.go", "mcp_reconcile.go"} {
|
||||
path := filepath.Join("..", "..", "..", "internal", "app", "archied", name)
|
||||
source, readErr := os.ReadFile(path)
|
||||
if readErr == nil {
|
||||
text.WriteString(string(source))
|
||||
}
|
||||
}
|
||||
|
||||
for _, required := range []string{
|
||||
// The provider registry, its engines and the consumer wiring live
|
||||
// in bootstrap.go (the boot-phase carrier) since the composition
|
||||
// root was decomposed; the receiver makes the arg expressions
|
||||
// carry the b. prefix there.
|
||||
"toolprovider.NewRegistry(b.toolReg)",
|
||||
// buildMCPProvider is the single construction seam: boot registration
|
||||
// and the live reconciliation both reach configuredMCPProvider through
|
||||
// it, so an MCP server is always built with the daemon's sampling
|
||||
// handler.
|
||||
"configuredMCPProvider(srv, b.cfgHolder.Get().WorkDir, b.mcpSamplingHandler())",
|
||||
"b.buildMCPProvider(srv)",
|
||||
"capabilityHost.Register(b.providerRegistry)",
|
||||
// The chat turn builds its toolset from the registry before the
|
||||
// system prompt is rendered, so the prompt can advertise exactly
|
||||
// the tools the model is handed. After the structural refactor these
|
||||
// calls live in the chat composition files.
|
||||
"chatGenerateOptions(ctx,",
|
||||
"toolSummaries(options.Tools)",
|
||||
} {
|
||||
if !strings.Contains(text.String(), required) {
|
||||
t.Errorf("archied wiring not found: %q", required)
|
||||
}
|
||||
}
|
||||
if strings.Contains(text.String(), ".RegisterTools(ctx, toolReg)") {
|
||||
t.Error("composition bypasses the typed provider registry with direct MCP registration")
|
||||
}
|
||||
if strings.Contains(text.String(), "NewLoopRunner") {
|
||||
t.Error("archied constructs a worker-local autonomous runner")
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
protocol "github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
)
|
||||
|
||||
func TestDesktopCommanderClientCompatibility(t *testing.T) {
|
||||
if os.Getenv("ARCHIE_TEST_DESKTOP_COMMANDER") != "1" {
|
||||
t.Skip("set ARCHIE_TEST_DESKTOP_COMMANDER=1 to run the external MCP integration")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||
defer cancel()
|
||||
|
||||
transport := protocol.NewStdioTransport(protocol.StdioTransportConfig{
|
||||
Command: "npx",
|
||||
Args: []string{
|
||||
"-y",
|
||||
"@wonderwhy-er/desktop-commander@0.2.46",
|
||||
"--no-onboarding",
|
||||
},
|
||||
Dir: "../../..",
|
||||
})
|
||||
provider := New("desktop-commander", transport, false)
|
||||
if err := provider.Start(ctx); err != nil {
|
||||
t.Fatalf("start Desktop Commander through MCP client: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
stopCtx, stopCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer stopCancel()
|
||||
if err := provider.Stop(stopCtx); err != nil {
|
||||
t.Errorf("stop Desktop Commander: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
entries, err := provider.Discover(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("discover Desktop Commander tools: %v", err)
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
t.Fatal("Desktop Commander advertised no tools")
|
||||
}
|
||||
required := map[string]bool{
|
||||
"mcp.desktop_commander.start_process": false,
|
||||
"mcp.desktop_commander.interact_with_process": false,
|
||||
"mcp.desktop_commander.read_process_output": false,
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if _, ok := required[entry.Name]; ok {
|
||||
required[entry.Name] = true
|
||||
}
|
||||
}
|
||||
for name, found := range required {
|
||||
if !found {
|
||||
t.Errorf("Desktop Commander did not advertise required shell tool %q", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,550 +0,0 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
protocol "github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
toolprovider "github.com/samcharles93/archie-core/internal/tools/provider"
|
||||
)
|
||||
|
||||
func TestProviderInitializesDiscoversAndCallsOriginalMCPTool(t *testing.T) {
|
||||
transport := newFakeTransport()
|
||||
transport.listed = []protocol.ToolSchema{{
|
||||
Name: "Search Repos!",
|
||||
Description: "Search repositories",
|
||||
InputSchema: tools.JSONSchema{"type": "object"},
|
||||
}}
|
||||
provider := New("Git Hub/Prod", transport, false)
|
||||
|
||||
manifest := provider.Manifest()
|
||||
if manifest.ID != "mcp.git-hub-prod" {
|
||||
t.Fatalf("Manifest().ID = %q, want mcp.git-hub-prod", manifest.ID)
|
||||
}
|
||||
if err := manifest.Validate(); err != nil {
|
||||
t.Fatalf("Manifest().Validate() = %v", err)
|
||||
}
|
||||
if err := provider.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := transport.notifications(); len(got) != 1 || got[0] != "notifications/initialized" {
|
||||
t.Fatalf("notifications = %v, want initialized", got)
|
||||
}
|
||||
|
||||
entries, err := provider.Discover(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 1 {
|
||||
t.Fatalf("Discover() count = %d, want 1", len(entries))
|
||||
}
|
||||
entry := entries[0]
|
||||
if entry.Name != "mcp.git_hub_prod.search_repos" {
|
||||
t.Fatalf("tool name = %q, want sanitized mapped name", entry.Name)
|
||||
}
|
||||
if entry.Toolset != "mcp" || entry.Description != transport.listed[0].Description {
|
||||
t.Fatalf("tool metadata = %+v", entry)
|
||||
}
|
||||
|
||||
got, err := entry.Handler(context.Background(), map[string]any{"query": "archie"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != "firstsecond" {
|
||||
t.Fatalf("handler result = %v, want concatenated MCP text", got)
|
||||
}
|
||||
name, args := transport.lastCall()
|
||||
if name != "Search Repos!" || args["query"] != "archie" {
|
||||
t.Fatalf("MCP call = %q %#v, want original name and args", name, args)
|
||||
}
|
||||
if err := provider.Stop(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if transport.State() != protocol.StateStopped {
|
||||
t.Fatalf("transport state = %s, want stopped", transport.State())
|
||||
}
|
||||
}
|
||||
|
||||
// callOverlapWindow bounds how long a test gives tool calls to reach the
|
||||
// transport. A call allowed to overlap gets there microseconds after its
|
||||
// goroutine starts, so one still absent after this window is held back by
|
||||
// the client, not by the scheduler.
|
||||
const callOverlapWindow = 500 * time.Millisecond
|
||||
|
||||
// reachedSend reports how many of n calls reached Send within window.
|
||||
func reachedSend(entered <-chan struct{}, n int, window time.Duration) int {
|
||||
count := 0
|
||||
for range n {
|
||||
select {
|
||||
case <-entered:
|
||||
count++
|
||||
case <-time.After(window):
|
||||
return count
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// TestProviderParallelToolCallsReachTheMCPClient pins the wiring half of the
|
||||
// per-server flag: the choice made at construction has to reach the client
|
||||
// the provider builds in Start, or a server that opted in stays serialized
|
||||
// with no other symptom.
|
||||
func TestProviderParallelToolCallsReachTheMCPClient(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
parallelToolCalls bool
|
||||
wantInFlight int
|
||||
}{
|
||||
{
|
||||
name: "provider for a server that has not opted in keeps one tool call in flight",
|
||||
wantInFlight: 1,
|
||||
},
|
||||
{
|
||||
name: "provider for an opted-in server overlaps tool calls",
|
||||
parallelToolCalls: true,
|
||||
wantInFlight: 2,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
transport := newFakeTransport()
|
||||
transport.listed = []protocol.ToolSchema{{Name: "slow"}}
|
||||
transport.callEntered = make(chan struct{}, 2)
|
||||
transport.callRelease = make(chan struct{})
|
||||
provider := New("slow-server", transport, tt.parallelToolCalls)
|
||||
if err := provider.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entries, err := provider.Discover(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 1 {
|
||||
t.Fatalf("Discover() count = %d, want 1", len(entries))
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for range 2 {
|
||||
wg.Go(func() {
|
||||
if _, err := entries[0].Handler(context.Background(), nil); err != nil {
|
||||
t.Errorf("handler: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if got := reachedSend(transport.callEntered, 2, callOverlapWindow); got != tt.wantInFlight {
|
||||
t.Fatalf("tool calls in flight at once = %d, want %d", got, tt.wantInFlight)
|
||||
}
|
||||
|
||||
close(transport.callRelease)
|
||||
wg.Wait()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderSurfacesMCPToolLevelErrors(t *testing.T) {
|
||||
transport := newFakeTransport()
|
||||
transport.listed = []protocol.ToolSchema{{Name: "fails"}}
|
||||
transport.callResult = protocol.CallToolResult{
|
||||
Content: []protocol.ContentBlock{{Type: "text", Text: "denied"}},
|
||||
IsError: true,
|
||||
}
|
||||
provider := New("errors", transport, false)
|
||||
if err := provider.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entries, err := provider.Discover(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 1 {
|
||||
t.Fatalf("Discover() count = %d, want 1", len(entries))
|
||||
}
|
||||
|
||||
if _, err := entries[0].Handler(context.Background(), nil); err == nil ||
|
||||
!strings.Contains(err.Error(), "denied") {
|
||||
t.Fatalf("handler error = %v, want MCP tool failure content", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderPreservesResourceTextAndMultimodalResults(t *testing.T) {
|
||||
transport := newFakeTransport()
|
||||
transport.listed = []protocol.ToolSchema{{Name: "capture"}}
|
||||
transport.callResult = protocol.CallToolResult{Content: []protocol.ContentBlock{
|
||||
{Type: "text", Text: "captured"},
|
||||
{Type: "resource", Resource: &protocol.ResourceContent{Text: " resource context"}},
|
||||
{Type: "image", Data: "aW1hZ2U=", MimeType: "image/png"},
|
||||
}}
|
||||
provider := New("media", transport, false)
|
||||
if err := provider.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entries, err := provider.Discover(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
output, err := entries[0].Handler(context.Background(), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, ok := output.(tools.MultimodalResult)
|
||||
if !ok {
|
||||
t.Fatalf("handler result type = %T, want tools.MultimodalResult", output)
|
||||
}
|
||||
if !result.IsMultimodal || result.Summary != "captured resource context" {
|
||||
t.Fatalf("multimodal result = %+v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderWritesBinaryContentToDeliverableMediaRefs(t *testing.T) {
|
||||
transport := newFakeTransport()
|
||||
transport.listed = []protocol.ToolSchema{{Name: "media"}}
|
||||
transport.callResult = protocol.CallToolResult{Content: []protocol.ContentBlock{
|
||||
{Type: "text", Text: "summary "},
|
||||
{Type: "image", Data: "aW1hZ2U=", MimeType: "image/png"},
|
||||
{Type: "audio", Data: "YXVkaW8=", MimeType: "audio/wav"},
|
||||
{Type: "resource", Resource: &protocol.ResourceContent{MimeType: "application/pdf", Blob: "cGRm"}},
|
||||
}}
|
||||
provider := New("media", transport, false)
|
||||
if err := provider.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = provider.Stop(context.Background()) })
|
||||
|
||||
entries, err := provider.Discover(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 1 {
|
||||
t.Fatalf("Discover() count = %d, want 1", len(entries))
|
||||
}
|
||||
|
||||
output, err := entries[0].Handler(context.Background(), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, ok := output.(tools.MultimodalResult)
|
||||
if !ok {
|
||||
t.Fatalf("handler result type = %T, want tools.MultimodalResult", output)
|
||||
}
|
||||
if !result.IsMultimodal {
|
||||
t.Error("IsMultimodal = false, want true")
|
||||
}
|
||||
if result.Summary != "summary " {
|
||||
t.Errorf("Summary = %q, want %q", result.Summary, "summary ")
|
||||
}
|
||||
if result.SubdirHint == "" {
|
||||
t.Fatal("SubdirHint is empty, want the written media directory")
|
||||
}
|
||||
if len(result.Files) != 3 {
|
||||
t.Fatalf("Files = %v, want 3 written files", result.Files)
|
||||
}
|
||||
if len(result.URLs) != 3 {
|
||||
t.Fatalf("URLs = %v, want 3 deliverable media refs", result.URLs)
|
||||
}
|
||||
|
||||
want := []struct {
|
||||
bytes []byte
|
||||
typ string
|
||||
}{
|
||||
{[]byte("image"), "image"},
|
||||
{[]byte("audio"), "audio"},
|
||||
{[]byte("pdf"), "document"},
|
||||
}
|
||||
for i, ref := range result.URLs {
|
||||
if ref.Path == "" {
|
||||
t.Fatalf("URLs[%d].Path is empty, want a local file for delivery", i)
|
||||
}
|
||||
if ref.Type != want[i].typ {
|
||||
t.Errorf("URLs[%d].Type = %q, want %q", i, ref.Type, want[i].typ)
|
||||
}
|
||||
got, err := os.ReadFile(ref.Path)
|
||||
if err != nil {
|
||||
t.Fatalf("URLs[%d].Path not readable: %v", i, err)
|
||||
}
|
||||
if string(got) != string(want[i].bytes) {
|
||||
t.Errorf("URLs[%d] bytes = %q, want %q", i, got, want[i].bytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderStartFailureStopsTransport(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
startErr error
|
||||
sendErr error
|
||||
wantStops int
|
||||
}{
|
||||
{name: "transport start", startErr: errors.New("start failed")},
|
||||
{name: "initialize", sendErr: errors.New("initialize failed"), wantStops: 1},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
transport := newFakeTransport()
|
||||
transport.startErr = tt.startErr
|
||||
transport.sendErr = tt.sendErr
|
||||
provider := New("failure", transport, false)
|
||||
if err := provider.Start(context.Background()); err == nil {
|
||||
t.Fatal("Start() succeeded")
|
||||
}
|
||||
if transport.stopCount != tt.wantStops {
|
||||
t.Fatalf("transport Stop() calls = %d, want %d", transport.stopCount, tt.wantStops)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderRejectsInvalidConfiguration(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
server string
|
||||
transport LifecycleTransport
|
||||
}{
|
||||
{name: "empty name", transport: newFakeTransport()},
|
||||
{name: "nil transport", server: "server"},
|
||||
{name: "typed nil transport", server: "server", transport: (*fakeTransport)(nil)},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
provider := New(tt.server, tt.transport, false)
|
||||
if err := provider.Start(context.Background()); err == nil {
|
||||
t.Fatal("Start() succeeded")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderSatisfiesEngine(t *testing.T) {
|
||||
var _ toolprovider.Engine = New("compile", newFakeTransport(), false)
|
||||
}
|
||||
|
||||
// Compile-time checks: HTTP and SSE transports satisfy LifecycleTransport.
|
||||
func TestTransportsSatisfyLifecycleTransport(t *testing.T) {
|
||||
var _ LifecycleTransport = (*protocol.HTTPTransport)(nil)
|
||||
var _ LifecycleTransport = (*protocol.SSETransport)(nil)
|
||||
// Also check StdioTransport, which already satisfied it.
|
||||
var _ LifecycleTransport = (*protocol.StdioTransport)(nil)
|
||||
}
|
||||
|
||||
func TestSanitizeSegmentsAreDeterministicASCII(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
manifest string
|
||||
tool string
|
||||
}{
|
||||
{name: "spaces symbols and unicode", input: " 42 Répo/搜索 ", manifest: "x-42-r-po", tool: "x_42_r_po"},
|
||||
{name: "separator runs", input: "A...B", manifest: "a-b", tool: "a_b"},
|
||||
{name: "no identifier content", input: "---", manifest: "", tool: ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := sanitizeManifestSegment(tt.input); got != tt.manifest {
|
||||
t.Fatalf("sanitizeManifestSegment(%q) = %q, want %q", tt.input, got, tt.manifest)
|
||||
}
|
||||
if got := sanitizeToolSegment(tt.input); got != tt.tool {
|
||||
t.Fatalf("sanitizeToolSegment(%q) = %q, want %q", tt.input, got, tt.tool)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type fakeTransport struct {
|
||||
mu sync.Mutex
|
||||
|
||||
state protocol.TransportState
|
||||
startErr error
|
||||
sendErr error
|
||||
stopErr error
|
||||
stopCount int
|
||||
listed []protocol.ToolSchema
|
||||
callResult protocol.CallToolResult
|
||||
notifyMethods []string
|
||||
calledName string
|
||||
calledArgs map[string]any
|
||||
|
||||
// callEntered receives one token per tools/call that reaches Send, and
|
||||
// the call then blocks until callRelease is closed. Set both before
|
||||
// Start to hold tool calls open and observe how many the client let
|
||||
// overlap.
|
||||
callEntered chan struct{}
|
||||
callRelease chan struct{}
|
||||
|
||||
// serverRequestHandler is captured from the client at construction; a
|
||||
// test invokes it to stand in for a server-initiated request.
|
||||
serverRequestHandler protocol.ServerRequestHandler
|
||||
}
|
||||
|
||||
func (t *fakeTransport) SetServerRequestHandler(handler protocol.ServerRequestHandler) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.serverRequestHandler = handler
|
||||
}
|
||||
|
||||
func newFakeTransport() *fakeTransport {
|
||||
return &fakeTransport{
|
||||
state: protocol.StateStopped,
|
||||
callResult: protocol.CallToolResult{
|
||||
Content: []protocol.ContentBlock{
|
||||
{Type: "text", Text: "first"},
|
||||
{Type: "text", Text: "second"},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (t *fakeTransport) Start(context.Context) error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if t.startErr != nil {
|
||||
return t.startErr
|
||||
}
|
||||
t.state = protocol.StateRunning
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *fakeTransport) Stop(context.Context) error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.stopCount++
|
||||
t.state = protocol.StateStopped
|
||||
return t.stopErr
|
||||
}
|
||||
|
||||
func (t *fakeTransport) State() protocol.TransportState {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return t.state
|
||||
}
|
||||
|
||||
func (t *fakeTransport) Send(_ context.Context, body []byte) ([]byte, error) {
|
||||
var request struct {
|
||||
ID json.RawMessage `json:"id"`
|
||||
Method string `json:"method"`
|
||||
Params json.RawMessage `json:"params"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &request); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Outside the lock: holding it here would serialize the calls this hook
|
||||
// exists to observe, making a parallel client look serialized.
|
||||
if request.Method == "tools/call" {
|
||||
if t.callEntered != nil {
|
||||
t.callEntered <- struct{}{}
|
||||
}
|
||||
if t.callRelease != nil {
|
||||
<-t.callRelease
|
||||
}
|
||||
}
|
||||
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if t.sendErr != nil {
|
||||
return nil, t.sendErr
|
||||
}
|
||||
var result any
|
||||
switch request.Method {
|
||||
case "initialize":
|
||||
result = protocol.InitializeResult{
|
||||
ProtocolVersion: "2024-11-05",
|
||||
ServerInfo: protocol.ServerInfo{Name: "fake", Version: "1.0.0"},
|
||||
Capabilities: protocol.Capabilities{Tools: json.RawMessage(`{}`)},
|
||||
}
|
||||
case "tools/list":
|
||||
result = map[string]any{"tools": t.listed}
|
||||
case "tools/call":
|
||||
var params struct {
|
||||
Name string `json:"name"`
|
||||
Arguments map[string]any `json:"arguments"`
|
||||
}
|
||||
if err := json.Unmarshal(request.Params, ¶ms); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.calledName = params.Name
|
||||
t.calledArgs = params.Arguments
|
||||
result = t.callResult
|
||||
default:
|
||||
return nil, errors.New("unexpected method: " + request.Method)
|
||||
}
|
||||
resultJSON, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(protocol.Message{
|
||||
JSONRPC: "2.0",
|
||||
ID: request.ID,
|
||||
Result: resultJSON,
|
||||
})
|
||||
}
|
||||
|
||||
// TestProviderWiresSamplingHandlerToClient proves the handler a daemon
|
||||
// supplies reaches the client the provider builds, so a server-initiated
|
||||
// sampling request is answered from the daemon's model path rather than
|
||||
// refused (or silently dropped).
|
||||
func TestProviderWiresSamplingHandlerToClient(t *testing.T) {
|
||||
transport := newFakeTransport()
|
||||
provider := New("sampling-server", transport, false, WithSamplingHandler(
|
||||
func(context.Context, protocol.SamplingRequest) (protocol.SamplingResult, error) {
|
||||
return protocol.SamplingResult{
|
||||
Model: "openai/gpt-5.6",
|
||||
Role: "assistant",
|
||||
Content: protocol.SamplingContent{Type: "text", Text: "four"},
|
||||
}, nil
|
||||
},
|
||||
))
|
||||
if err := provider.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
|
||||
handler := transport.serverRequestHandler
|
||||
if handler == nil {
|
||||
t.Fatal("provider did not pass the sampling handler to its client")
|
||||
}
|
||||
result, rpcErr := handler(context.Background(), "sampling/createMessage",
|
||||
json.RawMessage(`{"messages":[{"role":"user","content":{"type":"text","text":"2+2?"}}]}`))
|
||||
if rpcErr != nil {
|
||||
t.Fatalf("sampling answered with RPC error %+v, want a result", rpcErr)
|
||||
}
|
||||
var decoded protocol.SamplingResult
|
||||
if err := json.Unmarshal(result, &decoded); err != nil {
|
||||
t.Fatalf("unmarshal result: %v", err)
|
||||
}
|
||||
if decoded.Content.Text != "four" {
|
||||
t.Errorf("sampling result = %+v, want the handler's completion", decoded)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *fakeTransport) Notify(_ context.Context, body []byte) error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
var notification struct {
|
||||
Method string `json:"method"`
|
||||
}
|
||||
if err := json.Unmarshal(body, ¬ification); err != nil {
|
||||
return err
|
||||
}
|
||||
t.notifyMethods = append(t.notifyMethods, notification.Method)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *fakeTransport) notifications() []string {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return append([]string(nil), t.notifyMethods...)
|
||||
}
|
||||
|
||||
func (t *fakeTransport) lastCall() (string, map[string]any) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return t.calledName, t.calledArgs
|
||||
}
|
||||
@@ -1,289 +0,0 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/plugin"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// Atomic rollback is right for a provider the daemon requires. It is wrong
|
||||
// for an external MCP server pulled from a registry at runtime -- exactly the
|
||||
// category that is allowed to be absent.
|
||||
//
|
||||
// Observed on carina 2026-07-30: mcp.desktop-commander could not start
|
||||
// (missing unzip in the runtime image) and archied crash-looped under
|
||||
// Restart=on-failure, losing chat, the gateway and every builtin tool over
|
||||
// one third-party npm package.
|
||||
func TestOptionalProviderFailureDoesNotStopTheFamily(t *testing.T) {
|
||||
failure := errors.New("npx: command not found")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
// break is applied to the optional engine.
|
||||
breakEngine func(*fakeEngine)
|
||||
wantReason string
|
||||
}{
|
||||
{
|
||||
name: "start fails",
|
||||
breakEngine: func(e *fakeEngine) { e.startErr = failure },
|
||||
wantReason: "npx",
|
||||
},
|
||||
{
|
||||
name: "discover fails",
|
||||
breakEngine: func(e *fakeEngine) { e.discoverErr = failure },
|
||||
wantReason: "npx",
|
||||
},
|
||||
{
|
||||
name: "start panics",
|
||||
breakEngine: func(e *fakeEngine) { e.startPanic = "boom" },
|
||||
wantReason: "boom",
|
||||
},
|
||||
{
|
||||
name: "discover panics",
|
||||
breakEngine: func(e *fakeEngine) { e.discoverPanic = "boom" },
|
||||
wantReason: "boom",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
index := tools.NewRegistry()
|
||||
registry := NewRegistry(index)
|
||||
|
||||
required := newFakeEngine("builtin")
|
||||
required.tools = []tools.ToolEntry{testTool("read"), testTool("shell")}
|
||||
if err := registry.Register(required); err != nil {
|
||||
t.Fatalf("Register(required): %v", err)
|
||||
}
|
||||
|
||||
optional := newFakeEngine("mcp.desktop-commander")
|
||||
optional.tools = []tools.ToolEntry{testTool("desktop")}
|
||||
tc.breakEngine(optional)
|
||||
if err := registry.RegisterOptional(optional); err != nil {
|
||||
t.Fatalf("RegisterOptional: %v", err)
|
||||
}
|
||||
|
||||
if err := registry.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start returned %v; an optional provider failing must not "+
|
||||
"fail the family, or the daemon exits and crash-loops", err)
|
||||
}
|
||||
|
||||
// The builtins must still be there. This is the whole point.
|
||||
for _, name := range []string{"read", "shell"} {
|
||||
if _, ok := index.Get(name); !ok {
|
||||
t.Errorf("tool %q is missing: an optional provider's failure "+
|
||||
"rolled back the required providers", name)
|
||||
}
|
||||
}
|
||||
// The failed provider's tools must not be half-registered.
|
||||
if _, ok := index.Get("desktop"); ok {
|
||||
t.Error("tool \"desktop\" is registered despite its provider failing")
|
||||
}
|
||||
|
||||
skipped := registry.Skipped()
|
||||
if len(skipped) != 1 {
|
||||
t.Fatalf("Skipped() = %v, want exactly the failed provider", skipped)
|
||||
}
|
||||
if skipped[0].ID != "mcp.desktop-commander" {
|
||||
t.Errorf("Skipped()[0].ID = %q, want %q", skipped[0].ID, "mcp.desktop-commander")
|
||||
}
|
||||
if skipped[0].Err == nil {
|
||||
t.Error("Skipped()[0].Err is nil: the operator has nothing to act on")
|
||||
} else if !strings.Contains(skipped[0].Err.Error(), tc.wantReason) {
|
||||
t.Errorf("Skipped()[0].Err = %v, want it to mention %q", skipped[0].Err, tc.wantReason)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A required provider keeps today's all-or-nothing semantics.
|
||||
func TestRequiredProviderFailureStillRollsBack(t *testing.T) {
|
||||
index := tools.NewRegistry()
|
||||
registry := NewRegistry(index)
|
||||
|
||||
healthy := newFakeEngine("builtin")
|
||||
healthy.tools = []tools.ToolEntry{testTool("read")}
|
||||
if err := registry.Register(healthy); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
broken := newFakeEngine("required-thing")
|
||||
broken.startErr = errors.New("nope")
|
||||
if err := registry.Register(broken); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := registry.Start(context.Background()); err == nil {
|
||||
t.Fatal("Start returned nil; a required provider failing must still fail the family")
|
||||
}
|
||||
if _, ok := index.Get("read"); ok {
|
||||
t.Error("tool \"read\" survived: the required-provider rollback no longer rolls back")
|
||||
}
|
||||
}
|
||||
|
||||
// Dependencies of a skipped provider cannot run either. An optional dependent
|
||||
// is skipped with the reason; a required dependent is a hard failure, because
|
||||
// it declared it cannot work without something that is now absent.
|
||||
func TestSkippedProviderCascadesToDependents(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
dependentOptional bool
|
||||
wantStartErr bool
|
||||
wantSkippedIDs []string
|
||||
}{
|
||||
{
|
||||
name: "optional dependent is skipped too",
|
||||
dependentOptional: true,
|
||||
wantSkippedIDs: []string{"dependent", "flaky"},
|
||||
},
|
||||
{
|
||||
name: "required dependent fails the family",
|
||||
wantStartErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
index := tools.NewRegistry()
|
||||
registry := NewRegistry(index)
|
||||
|
||||
flaky := newFakeEngine("flaky")
|
||||
flaky.startErr = errors.New("unavailable")
|
||||
if err := registry.RegisterOptional(flaky); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dependent := engineWithDependencies("dependent", "flaky")
|
||||
dependent.tools = []tools.ToolEntry{testTool("dependent-tool")}
|
||||
var err error
|
||||
if tc.dependentOptional {
|
||||
err = registry.RegisterOptional(dependent)
|
||||
} else {
|
||||
err = registry.Register(dependent)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
startErr := registry.Start(context.Background())
|
||||
if tc.wantStartErr {
|
||||
if startErr == nil {
|
||||
t.Fatal("Start returned nil; a required provider depending on an " +
|
||||
"unavailable one must fail rather than run without it")
|
||||
}
|
||||
return
|
||||
}
|
||||
if startErr != nil {
|
||||
t.Fatalf("Start: %v", startErr)
|
||||
}
|
||||
if _, ok := index.Get("dependent-tool"); ok {
|
||||
t.Error("a provider whose dependency was skipped was started anyway")
|
||||
}
|
||||
|
||||
got := make([]string, 0, len(registry.Skipped()))
|
||||
for _, s := range registry.Skipped() {
|
||||
got = append(got, s.ID)
|
||||
}
|
||||
slices.Sort(got)
|
||||
slices.Sort(tc.wantSkippedIDs)
|
||||
if !slices.Equal(got, tc.wantSkippedIDs) {
|
||||
t.Errorf("Skipped() = %v, want %v", got, tc.wantSkippedIDs)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// All-optional-and-all-failing is still a successful start: the daemon runs
|
||||
// with its builtins and nothing else, which is the degraded state we want
|
||||
// rather than no daemon at all.
|
||||
func TestEveryOptionalProviderFailing(t *testing.T) {
|
||||
index := tools.NewRegistry()
|
||||
registry := NewRegistry(index)
|
||||
|
||||
for _, id := range []string{"mcp.one", "mcp.two"} {
|
||||
engine := newFakeEngine(id)
|
||||
engine.startErr = errors.New("gone")
|
||||
if err := registry.RegisterOptional(engine); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := registry.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
if len(registry.Skipped()) != 2 {
|
||||
t.Errorf("Skipped() = %v, want both providers", registry.Skipped())
|
||||
}
|
||||
if err := registry.Stop(context.Background()); err != nil {
|
||||
t.Errorf("Stop: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A failed optional provider must still be stopped, or a half-started child
|
||||
// process is left behind for the daemon's lifetime.
|
||||
func TestSkippedOptionalProviderIsCleanedUp(t *testing.T) {
|
||||
registry := NewRegistry(tools.NewRegistry())
|
||||
|
||||
optional := newFakeEngine("mcp.leaky")
|
||||
optional.discoverErr = errors.New("no tools")
|
||||
if err := registry.RegisterOptional(optional); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := registry.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
if optional.stopCount != 1 {
|
||||
t.Errorf("stopCount = %d, want 1: a provider that started but failed to "+
|
||||
"discover must be stopped, not abandoned", optional.stopCount)
|
||||
}
|
||||
}
|
||||
|
||||
// The carina failure, reproduced through the capability host -- the path
|
||||
// main.go actually calls, and the one that returned the error that exited the
|
||||
// daemon. Registering desktop-commander as required makes this fail with
|
||||
// `start plugin module "archie.tools": ... unzip: not found`, which is
|
||||
// verbatim what crash-looped archied on 2026-07-30.
|
||||
func TestCarinaScenarioThroughCapabilityHost(t *testing.T) {
|
||||
index := tools.NewRegistry()
|
||||
registry := NewRegistry(index)
|
||||
|
||||
builtins := newFakeEngine("archie.tools.builtin")
|
||||
builtins.tools = []tools.ToolEntry{testTool("read"), testTool("shell"), testTool("edit")}
|
||||
if err := registry.Register(builtins); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
memory := newFakeEngine("archie.tools.memory")
|
||||
memory.tools = []tools.ToolEntry{testTool("memory_edit")}
|
||||
if err := registry.Register(memory); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
desktop := newFakeEngine("mcp.desktop-commander")
|
||||
desktop.startErr = errors.New("npx exec: unzip: not found")
|
||||
if err := registry.RegisterOptional(desktop); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
host := plugin.NewHost()
|
||||
if err := host.Register(registry); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := host.Start(context.Background()); err != nil {
|
||||
t.Fatalf("capability host startup failed: %v\n"+
|
||||
"main.go logs 'capability host startup' and returns 1 here, which "+
|
||||
"under Restart=on-failure is the crash loop", err)
|
||||
}
|
||||
|
||||
// Everything the operator actually depends on is still there.
|
||||
for _, name := range []string{"read", "shell", "edit", "memory_edit"} {
|
||||
if _, ok := index.Get(name); !ok {
|
||||
t.Errorf("tool %q was lost to a third-party npm package", name)
|
||||
}
|
||||
}
|
||||
if err := host.Stop(context.Background()); err != nil {
|
||||
t.Errorf("Stop: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,478 +0,0 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/plugin"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
func TestRegistryRegisterAndGet(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
engine Engine
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "valid", engine: newFakeEngine("valid")},
|
||||
{name: "nil", wantErr: true},
|
||||
{
|
||||
name: "invalid manifest",
|
||||
engine: &fakeEngine{manifest: plugin.Manifest{
|
||||
ID: "INVALID",
|
||||
}},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "wrong capability",
|
||||
engine: &fakeEngine{manifest: testManifest(
|
||||
"channel-provider",
|
||||
[]plugin.CapabilityKind{"channels"},
|
||||
nil,
|
||||
)},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
registry := NewRegistry(tools.NewRegistry())
|
||||
err := registry.Register(tt.engine)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("Register() error = %v, wantErr %t", err, tt.wantErr)
|
||||
}
|
||||
if tt.wantErr {
|
||||
return
|
||||
}
|
||||
got, ok := registry.Get(tt.engine.Manifest().ID)
|
||||
if !ok || got != tt.engine {
|
||||
t.Fatalf("Get() = (%v, %t), want registered engine", got, ok)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryRejectsDuplicateAndLateRegistration(t *testing.T) {
|
||||
registry := NewRegistry(tools.NewRegistry())
|
||||
first := newFakeEngine("duplicate")
|
||||
if err := registry.Register(first); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := registry.Register(newFakeEngine("duplicate")); err == nil {
|
||||
t.Fatal("duplicate provider was accepted")
|
||||
}
|
||||
if err := registry.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := registry.Register(newFakeEngine("late")); err == nil {
|
||||
t.Fatal("provider registration after start was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryStartsInDependencyOrderAndStopsInReverse(t *testing.T) {
|
||||
index := tools.NewRegistry()
|
||||
registry := NewRegistry(index)
|
||||
var calls callLog
|
||||
|
||||
first := newFakeEngine("first")
|
||||
first.calls = &calls
|
||||
first.tools = []tools.ToolEntry{testTool("first.tool")}
|
||||
|
||||
second := newFakeEngine("second")
|
||||
second.manifest.Dependencies = []string{"first"}
|
||||
second.calls = &calls
|
||||
second.tools = []tools.ToolEntry{testTool("second.tool")}
|
||||
|
||||
for _, engine := range []Engine{second, first} {
|
||||
if err := registry.Register(engine); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := registry.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, want := calls.snapshot(), []string{
|
||||
"start:first", "discover:first",
|
||||
"start:second", "discover:second",
|
||||
}; !slices.Equal(got, want) {
|
||||
t.Fatalf("startup calls = %v, want %v", got, want)
|
||||
}
|
||||
for _, name := range []string{"first.tool", "second.tool"} {
|
||||
if _, ok := index.Get(name); !ok {
|
||||
t.Fatalf("tool %q was not indexed", name)
|
||||
}
|
||||
}
|
||||
|
||||
if err := registry.Stop(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, want := calls.snapshot(), []string{
|
||||
"start:first", "discover:first",
|
||||
"start:second", "discover:second",
|
||||
"stop:second", "stop:first",
|
||||
}; !slices.Equal(got, want) {
|
||||
t.Fatalf("lifecycle calls = %v, want %v", got, want)
|
||||
}
|
||||
if got := index.All(); len(got) != 0 {
|
||||
t.Fatalf("tools remain after stop: %v", toolNames(got))
|
||||
}
|
||||
if err := registry.Stop(context.Background()); err != nil {
|
||||
t.Fatalf("second Stop() = %v, want idempotent success", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryStartRejectsMissingAndCyclicDependencies(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
engines []*fakeEngine
|
||||
}{
|
||||
{
|
||||
name: "missing",
|
||||
engines: []*fakeEngine{
|
||||
engineWithDependencies("one", "absent"),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "cycle",
|
||||
engines: []*fakeEngine{
|
||||
engineWithDependencies("one", "two"),
|
||||
engineWithDependencies("two", "one"),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
registry := NewRegistry(tools.NewRegistry())
|
||||
for _, engine := range tt.engines {
|
||||
if err := registry.Register(engine); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := registry.Start(context.Background()); err == nil {
|
||||
t.Fatal("Start() succeeded, want dependency error")
|
||||
}
|
||||
for _, engine := range tt.engines {
|
||||
if engine.startCount != 0 {
|
||||
t.Fatalf("provider %q started despite invalid dependency graph", engine.manifest.ID)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryStartRollsBackOnProviderFailures(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
configure func(first, second *fakeEngine)
|
||||
preexisting []tools.ToolEntry
|
||||
}{
|
||||
{
|
||||
name: "start error",
|
||||
configure: func(_, second *fakeEngine) {
|
||||
second.startErr = errors.New("start failed")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "start panic",
|
||||
configure: func(_, second *fakeEngine) {
|
||||
second.startPanic = "start panic"
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "discovery error",
|
||||
configure: func(_, second *fakeEngine) {
|
||||
second.discoverErr = errors.New("discover failed")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "discovery panic",
|
||||
configure: func(_, second *fakeEngine) {
|
||||
second.discoverPanic = "discover panic"
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "tool collision",
|
||||
configure: func(_, second *fakeEngine) {
|
||||
second.tools = []tools.ToolEntry{
|
||||
testTool("new.before.collision"),
|
||||
testTool("taken"),
|
||||
}
|
||||
},
|
||||
preexisting: []tools.ToolEntry{testTool("taken")},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
index := tools.NewRegistry()
|
||||
for _, entry := range tt.preexisting {
|
||||
if err := index.Register(entry); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
registry := NewRegistry(index)
|
||||
first := newFakeEngine("first")
|
||||
first.tools = []tools.ToolEntry{testTool("first.tool")}
|
||||
second := engineWithDependencies("second", "first")
|
||||
second.tools = []tools.ToolEntry{testTool("second.tool")}
|
||||
tt.configure(first, second)
|
||||
for _, engine := range []Engine{first, second} {
|
||||
if err := registry.Register(engine); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := registry.Start(context.Background()); err == nil {
|
||||
t.Fatal("Start() succeeded, want failure")
|
||||
}
|
||||
if first.stopCount != 1 {
|
||||
t.Fatalf("first stop count = %d, want rollback stop", first.stopCount)
|
||||
}
|
||||
if second.startCount > 0 && second.stopCount != 1 {
|
||||
t.Fatalf("second stop count = %d after starting, want rollback stop", second.stopCount)
|
||||
}
|
||||
if _, ok := index.Get("first.tool"); ok {
|
||||
t.Fatal("first provider tool remains after rollback")
|
||||
}
|
||||
if _, ok := index.Get("new.before.collision"); ok {
|
||||
t.Fatal("partial colliding batch was registered")
|
||||
}
|
||||
if len(tt.preexisting) > 0 {
|
||||
if _, ok := index.Get("taken"); !ok {
|
||||
t.Fatal("preexisting colliding tool was removed")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryStopContinuesAndJoinsErrors(t *testing.T) {
|
||||
index := tools.NewRegistry()
|
||||
registry := NewRegistry(index)
|
||||
first := newFakeEngine("first")
|
||||
first.tools = []tools.ToolEntry{testTool("first.tool")}
|
||||
first.stopErr = errors.New("first stop")
|
||||
second := engineWithDependencies("second", "first")
|
||||
second.tools = []tools.ToolEntry{testTool("second.tool")}
|
||||
second.stopPanic = "second stop panic"
|
||||
for _, engine := range []Engine{first, second} {
|
||||
if err := registry.Register(engine); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := registry.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err := registry.Stop(context.Background())
|
||||
if err == nil {
|
||||
t.Fatal("Stop() error = nil, want joined stop failures")
|
||||
}
|
||||
if first.stopCount != 1 || second.stopCount != 1 {
|
||||
t.Fatalf("stop counts = (%d, %d), want both stopped", first.stopCount, second.stopCount)
|
||||
}
|
||||
if len(index.All()) != 0 {
|
||||
t.Fatal("tools remain indexed after failed provider stops")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryRetriesFailedProviderStops(t *testing.T) {
|
||||
stopFailure := errors.New("transient provider stop")
|
||||
index := tools.NewRegistry()
|
||||
registry := NewRegistry(index)
|
||||
engine := newFakeEngine("retry")
|
||||
engine.tools = []tools.ToolEntry{testTool("retry.tool")}
|
||||
engine.stopErrors = []error{stopFailure, nil}
|
||||
if err := registry.Register(engine); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := registry.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := registry.Stop(context.Background()); !errors.Is(err, stopFailure) {
|
||||
t.Fatalf("first Stop() error = %v, want %v", err, stopFailure)
|
||||
}
|
||||
if _, ok := index.Get("retry.tool"); ok {
|
||||
t.Fatal("tool remains available while its provider failed to stop")
|
||||
}
|
||||
if err := registry.Stop(context.Background()); err != nil {
|
||||
t.Fatalf("second Stop() error = %v, want retry success", err)
|
||||
}
|
||||
if engine.stopCount != 2 {
|
||||
t.Fatalf("provider Stop() calls = %d, want 2", engine.stopCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryRetriesFailedStartupRollback(t *testing.T) {
|
||||
cleanupFailure := errors.New("rollback stop failed")
|
||||
registry := NewRegistry(tools.NewRegistry())
|
||||
first := newFakeEngine("first")
|
||||
first.stopErrors = []error{cleanupFailure, nil}
|
||||
second := engineWithDependencies("second", "first")
|
||||
second.startErr = errors.New("second start failed")
|
||||
for _, engine := range []Engine{first, second} {
|
||||
if err := registry.Register(engine); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := registry.Start(context.Background()); !errors.Is(err, cleanupFailure) {
|
||||
t.Fatalf("Start() error = %v, want rollback cleanup failure", err)
|
||||
}
|
||||
if err := registry.Stop(context.Background()); err != nil {
|
||||
t.Fatalf("Stop() retry error = %v", err)
|
||||
}
|
||||
if first.stopCount != 2 {
|
||||
t.Fatalf("first provider Stop() calls = %d, want rollback plus retry", first.stopCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryStartupRollbackUsesBoundedDetachedContext(t *testing.T) {
|
||||
registry := NewRegistry(tools.NewRegistry())
|
||||
engine := newFakeEngine("bounded-cleanup")
|
||||
engine.startErr = errors.New("start failed")
|
||||
if err := registry.Register(engine); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
if err := registry.Start(ctx); err == nil {
|
||||
t.Fatal("Start() succeeded")
|
||||
}
|
||||
if len(engine.stopContextDeadlines) != 1 || !engine.stopContextDeadlines[0] {
|
||||
t.Fatalf("Stop() deadline flags = %v, want bounded cleanup", engine.stopContextDeadlines)
|
||||
}
|
||||
if got := engine.stopContextErrors[0]; got != nil {
|
||||
t.Fatalf("Stop() context error = %v, want detached original cancellation", got)
|
||||
}
|
||||
}
|
||||
|
||||
type fakeEngine struct {
|
||||
manifest plugin.Manifest
|
||||
tools []tools.ToolEntry
|
||||
startErr error
|
||||
discoverErr error
|
||||
stopErr error
|
||||
stopErrors []error
|
||||
startPanic any
|
||||
discoverPanic any
|
||||
stopPanic any
|
||||
startCount int
|
||||
discoverCount int
|
||||
stopCount int
|
||||
stopContextDeadlines []bool
|
||||
stopContextErrors []error
|
||||
calls *callLog
|
||||
}
|
||||
|
||||
func newFakeEngine(id string) *fakeEngine {
|
||||
return &fakeEngine{
|
||||
manifest: testManifest(id, []plugin.CapabilityKind{"tools"}, nil),
|
||||
}
|
||||
}
|
||||
|
||||
func engineWithDependencies(id string, dependencies ...string) *fakeEngine {
|
||||
engine := newFakeEngine(id)
|
||||
engine.manifest.Dependencies = dependencies
|
||||
return engine
|
||||
}
|
||||
|
||||
func testManifest(
|
||||
id string,
|
||||
capabilities []plugin.CapabilityKind,
|
||||
dependencies []string,
|
||||
) plugin.Manifest {
|
||||
return plugin.Manifest{
|
||||
ID: id,
|
||||
Name: id,
|
||||
Version: "1.0.0",
|
||||
APIVersion: plugin.HostAPIVersion,
|
||||
Capabilities: capabilities,
|
||||
Dependencies: dependencies,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *fakeEngine) Manifest() plugin.Manifest {
|
||||
return e.manifest
|
||||
}
|
||||
|
||||
func (e *fakeEngine) Start(context.Context) error {
|
||||
e.startCount++
|
||||
e.log("start")
|
||||
if e.startPanic != nil {
|
||||
panic(e.startPanic)
|
||||
}
|
||||
return e.startErr
|
||||
}
|
||||
|
||||
func (e *fakeEngine) Discover(context.Context) ([]tools.ToolEntry, error) {
|
||||
e.discoverCount++
|
||||
e.log("discover")
|
||||
if e.discoverPanic != nil {
|
||||
panic(e.discoverPanic)
|
||||
}
|
||||
return e.tools, e.discoverErr
|
||||
}
|
||||
|
||||
func (e *fakeEngine) Stop(ctx context.Context) error {
|
||||
e.stopCount++
|
||||
e.log("stop")
|
||||
_, hasDeadline := ctx.Deadline()
|
||||
e.stopContextDeadlines = append(e.stopContextDeadlines, hasDeadline)
|
||||
e.stopContextErrors = append(e.stopContextErrors, ctx.Err())
|
||||
if e.stopPanic != nil {
|
||||
panic(e.stopPanic)
|
||||
}
|
||||
if len(e.stopErrors) >= e.stopCount {
|
||||
return e.stopErrors[e.stopCount-1]
|
||||
}
|
||||
return e.stopErr
|
||||
}
|
||||
|
||||
func (e *fakeEngine) log(operation string) {
|
||||
if e.calls != nil {
|
||||
e.calls.add(fmt.Sprintf("%s:%s", operation, e.manifest.ID))
|
||||
}
|
||||
}
|
||||
|
||||
type callLog struct {
|
||||
mu sync.Mutex
|
||||
calls []string
|
||||
}
|
||||
|
||||
func (l *callLog) add(call string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.calls = append(l.calls, call)
|
||||
}
|
||||
|
||||
func (l *callLog) snapshot() []string {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return append([]string(nil), l.calls...)
|
||||
}
|
||||
|
||||
func testTool(name string) tools.ToolEntry {
|
||||
return tools.ToolEntry{
|
||||
Name: name,
|
||||
Handler: func(context.Context, map[string]any) (any, error) {
|
||||
return name, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func toolNames(entries []tools.ToolEntry) []string {
|
||||
names := make([]string, len(entries))
|
||||
for i, entry := range entries {
|
||||
names[i] = entry.Name
|
||||
}
|
||||
slices.Sort(names)
|
||||
return names
|
||||
}
|
||||
@@ -1,231 +0,0 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// startRunningRegistry builds a registry over a fresh tool index with the
|
||||
// named engines registered and started as one family, the state a live
|
||||
// reconciliation runs against. It returns both so a test can read the index.
|
||||
func startRunningRegistry(t *testing.T, engines ...Engine) (*Registry, *tools.Registry) {
|
||||
t.Helper()
|
||||
index := tools.NewRegistry()
|
||||
registry := NewRegistry(index)
|
||||
for _, engine := range engines {
|
||||
if err := registry.RegisterOptional(engine); err != nil {
|
||||
t.Fatalf("RegisterOptional: %v", err)
|
||||
}
|
||||
}
|
||||
if err := registry.Start(t.Context()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
return registry, index
|
||||
}
|
||||
|
||||
func TestRegistryAddStartsOneProviderAlone(t *testing.T) {
|
||||
first := newFakeEngine("first")
|
||||
first.tools = []tools.ToolEntry{testTool("first.tool")}
|
||||
registry, index := startRunningRegistry(t, first)
|
||||
|
||||
second := newFakeEngine("second")
|
||||
second.tools = []tools.ToolEntry{testTool("second.tool")}
|
||||
if err := registry.Add(t.Context(), second); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
|
||||
if first.startCount != 1 || first.stopCount != 0 {
|
||||
t.Errorf("the running provider was disturbed: start=%d stop=%d", first.startCount, first.stopCount)
|
||||
}
|
||||
if second.startCount != 1 || second.discoverCount != 1 {
|
||||
t.Errorf("the added provider was not started: start=%d discover=%d", second.startCount, second.discoverCount)
|
||||
}
|
||||
if got := registry.RunningIDs(); !slices.Equal(got, []string{"first", "second"}) {
|
||||
t.Errorf("RunningIDs() = %v, want [first second]", got)
|
||||
}
|
||||
if _, ok := index.Get("second.tool"); !ok {
|
||||
t.Error("the added provider's tool was not indexed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryAddIsIsolatedWhenTheProviderFails(t *testing.T) {
|
||||
first := newFakeEngine("first")
|
||||
first.tools = []tools.ToolEntry{testTool("first.tool")}
|
||||
registry, _ := startRunningRegistry(t, first)
|
||||
|
||||
failing := newFakeEngine("second")
|
||||
failing.startErr = errors.New("boom")
|
||||
if err := registry.Add(t.Context(), failing); err == nil {
|
||||
t.Fatal("Add of a provider that cannot start: expected an error")
|
||||
}
|
||||
|
||||
if first.startCount != 1 || first.stopCount != 0 {
|
||||
t.Errorf("a failed addition rolled the family back: start=%d stop=%d", first.startCount, first.stopCount)
|
||||
}
|
||||
if _, ok := registry.Get("second"); ok {
|
||||
t.Error("the failed provider stayed registered")
|
||||
}
|
||||
if got := registry.RunningIDs(); !slices.Equal(got, []string{"first"}) {
|
||||
t.Errorf("RunningIDs() = %v, want the family unchanged", got)
|
||||
}
|
||||
if failing.stopCount == 0 {
|
||||
t.Error("the half-started provider was not cleaned up")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryAddBeforeStartRegistersForTheFamily(t *testing.T) {
|
||||
registry := NewRegistry(tools.NewRegistry())
|
||||
engine := newFakeEngine("late")
|
||||
if err := registry.Add(t.Context(), engine); err != nil {
|
||||
t.Fatalf("Add before Start: %v", err)
|
||||
}
|
||||
if registry.Running() {
|
||||
t.Error("Add before Start started the family")
|
||||
}
|
||||
if engine.startCount != 0 {
|
||||
t.Errorf("Add before Start started the engine %d times, want 0", engine.startCount)
|
||||
}
|
||||
if err := registry.Start(t.Context()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
if engine.startCount != 1 {
|
||||
t.Errorf("Start did not pick up the added provider: start=%d", engine.startCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryRemoveStopsOneProviderAlone(t *testing.T) {
|
||||
first := newFakeEngine("first")
|
||||
first.tools = []tools.ToolEntry{testTool("first.tool")}
|
||||
second := newFakeEngine("second")
|
||||
second.tools = []tools.ToolEntry{testTool("second.tool")}
|
||||
registry, index := startRunningRegistry(t, first, second)
|
||||
|
||||
if err := registry.Remove(t.Context(), "first"); err != nil {
|
||||
t.Fatalf("Remove: %v", err)
|
||||
}
|
||||
|
||||
if first.stopCount != 1 {
|
||||
t.Errorf("the removed provider was not stopped: stop=%d", first.stopCount)
|
||||
}
|
||||
if second.stopCount != 0 || second.startCount != 1 {
|
||||
t.Errorf("the surviving provider was disturbed: start=%d stop=%d", second.startCount, second.stopCount)
|
||||
}
|
||||
if _, ok := registry.Get("first"); ok {
|
||||
t.Error("the removed provider stayed registered")
|
||||
}
|
||||
if _, ok := index.Get("first.tool"); ok {
|
||||
t.Error("the removed provider's tool stayed indexed")
|
||||
}
|
||||
if _, ok := index.Get("second.tool"); !ok {
|
||||
t.Error("the surviving provider's tool left the index")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryRemoveRejectsUnknownProvider(t *testing.T) {
|
||||
registry, _ := startRunningRegistry(t)
|
||||
if err := registry.Remove(t.Context(), "missing"); err == nil {
|
||||
t.Fatal("Remove of an unregistered provider: expected an error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryReplaceSwapsTheRunningProvider(t *testing.T) {
|
||||
previous := newFakeEngine("mcp.alpha")
|
||||
previous.tools = []tools.ToolEntry{testTool("alpha.old")}
|
||||
registry, index := startRunningRegistry(t, previous)
|
||||
|
||||
replacement := newFakeEngine("mcp.alpha")
|
||||
replacement.tools = []tools.ToolEntry{testTool("alpha.new")}
|
||||
if err := registry.Replace(t.Context(), replacement); err != nil {
|
||||
t.Fatalf("Replace: %v", err)
|
||||
}
|
||||
|
||||
if previous.stopCount != 1 {
|
||||
t.Errorf("the replaced provider was not stopped: stop=%d", previous.stopCount)
|
||||
}
|
||||
if replacement.startCount != 1 {
|
||||
t.Errorf("the replacement was not started: start=%d", replacement.startCount)
|
||||
}
|
||||
if _, ok := index.Get("alpha.old"); ok {
|
||||
t.Error("the replaced provider's tool stayed indexed")
|
||||
}
|
||||
if _, ok := index.Get("alpha.new"); !ok {
|
||||
t.Error("the replacement's tool was not indexed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryReplaceRestoresThePreviousProviderOnFailure(t *testing.T) {
|
||||
previous := newFakeEngine("mcp.alpha")
|
||||
previous.tools = []tools.ToolEntry{testTool("alpha.old")}
|
||||
registry, index := startRunningRegistry(t, previous)
|
||||
|
||||
replacement := newFakeEngine("mcp.alpha")
|
||||
replacement.startErr = errors.New("boom")
|
||||
err := registry.Replace(t.Context(), replacement)
|
||||
if err == nil {
|
||||
t.Fatal("Replace with a provider that cannot start: expected an error")
|
||||
}
|
||||
|
||||
if previous.stopCount != 1 {
|
||||
t.Errorf("the previous provider was not stopped for the replacement: stop=%d", previous.stopCount)
|
||||
}
|
||||
if previous.startCount != 2 {
|
||||
t.Errorf("the previous provider was not restarted: start=%d, want 2", previous.startCount)
|
||||
}
|
||||
if _, ok := index.Get("alpha.old"); !ok {
|
||||
t.Error("the refused replacement left the previous provider's tool out of the index")
|
||||
}
|
||||
if got := registry.RunningIDs(); !slices.Equal(got, []string{"mcp.alpha"}) {
|
||||
t.Errorf("RunningIDs() = %v, want the previous provider still running", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryReplaceBeforeStartSwapsTheRegistration(t *testing.T) {
|
||||
registry := NewRegistry(tools.NewRegistry())
|
||||
previous := newFakeEngine("mcp.alpha")
|
||||
if err := registry.RegisterOptional(previous); err != nil {
|
||||
t.Fatalf("RegisterOptional: %v", err)
|
||||
}
|
||||
replacement := newFakeEngine("mcp.alpha")
|
||||
if err := registry.Replace(t.Context(), replacement); err != nil {
|
||||
t.Fatalf("Replace before Start: %v", err)
|
||||
}
|
||||
if err := registry.Start(t.Context()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
if replacement.startCount != 1 || previous.startCount != 0 {
|
||||
t.Errorf("Start ran the wrong registration: replacement=%d previous=%d", replacement.startCount, previous.startCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryRunningStateReads(t *testing.T) {
|
||||
registry := NewRegistry(tools.NewRegistry())
|
||||
engine := newFakeEngine("alpha")
|
||||
if err := registry.RegisterOptional(engine); err != nil {
|
||||
t.Fatalf("RegisterOptional: %v", err)
|
||||
}
|
||||
if registry.Running() {
|
||||
t.Error("Running() = true before Start")
|
||||
}
|
||||
if !registry.Has("alpha") {
|
||||
t.Error("Has(alpha) = false after registration")
|
||||
}
|
||||
if got := registry.RegisteredIDs(); !slices.Equal(got, []string{"alpha"}) {
|
||||
t.Errorf("RegisteredIDs() = %v, want [alpha]", got)
|
||||
}
|
||||
if got := registry.RunningIDs(); len(got) != 0 {
|
||||
t.Errorf("RunningIDs() = %v before Start, want none", got)
|
||||
}
|
||||
if err := registry.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
if !registry.Running() {
|
||||
t.Error("Running() = false after Start")
|
||||
}
|
||||
if got := registry.RunningIDs(); !slices.Equal(got, []string{"alpha"}) {
|
||||
t.Errorf("RunningIDs() = %v, want [alpha]", got)
|
||||
}
|
||||
}
|
||||
@@ -1,382 +0,0 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRegistryRegister(t *testing.T) {
|
||||
t.Run("valid entry", func(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
err := r.Register(ToolEntry{Name: "hello", Handler: noopHandler})
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
if len(r.All()) != 1 {
|
||||
t.Errorf("expected 1 tool, got %d", len(r.All()))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("duplicate name returns error", func(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
e := ToolEntry{Name: "dup", Handler: noopHandler}
|
||||
if err := r.Register(e); err != nil {
|
||||
t.Fatalf("first register: %v", err)
|
||||
}
|
||||
err := r.Register(e)
|
||||
if err == nil {
|
||||
t.Error("expected error for duplicate name")
|
||||
}
|
||||
if !errors.Is(err, ErrDuplicateTool) {
|
||||
t.Errorf("expected ErrDuplicateTool, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("invalid entry returns validation error", func(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
err := r.Register(ToolEntry{Name: ""})
|
||||
if err == nil {
|
||||
t.Error("expected validation error for empty name")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("multiple tools", func(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
for _, name := range []string{"a", "b", "c"} {
|
||||
if err := r.Register(ToolEntry{Name: name, Handler: noopHandler}); err != nil {
|
||||
t.Fatalf("register %q: %v", name, err)
|
||||
}
|
||||
}
|
||||
if len(r.All()) != 3 {
|
||||
t.Errorf("expected 3 tools, got %d", len(r.All()))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRegistryGet(t *testing.T) {
|
||||
t.Run("found", func(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
if err := r.Register(ToolEntry{Name: "hello", Description: "hi", Handler: noopHandler}); err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
e, ok := r.Get("hello")
|
||||
if !ok {
|
||||
t.Fatal("expected found=true")
|
||||
}
|
||||
if e.Name != "hello" || e.Description != "hi" {
|
||||
t.Errorf("Get returned %+v", e)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("not found", func(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
_, ok := r.Get("nonexistent")
|
||||
if ok {
|
||||
t.Error("expected found=false for unregistered name")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("returned entry is a defensive copy", func(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
if err := r.Register(ToolEntry{Name: "hello", Schema: JSONSchema{"type": "object"}, Handler: noopHandler}); err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
e, _ := r.Get("hello")
|
||||
e.Schema["type"] = "mutated"
|
||||
e2, _ := r.Get("hello")
|
||||
if e2.Schema["type"] != "object" {
|
||||
t.Errorf("Get did not defensively copy: registry's schema was mutated to %v", e2.Schema["type"])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRegistryAll(t *testing.T) {
|
||||
t.Run("empty registry", func(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
all := r.All()
|
||||
if len(all) != 0 {
|
||||
t.Errorf("expected 0 tools, got %d", len(all))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("returns copy of tools", func(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
_ = r.Register(ToolEntry{Name: "x", Handler: noopHandler})
|
||||
all := r.All()
|
||||
all[0].Name = "mutated"
|
||||
// Original registry must be unaffected.
|
||||
if r.All()[0].Name != "x" {
|
||||
t.Error("All() should return independent copies")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRegistryByToolset(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
_ = r.Register(ToolEntry{Name: "f1", Toolset: "file", Handler: noopHandler})
|
||||
_ = r.Register(ToolEntry{Name: "f2", Toolset: "file", Handler: noopHandler})
|
||||
_ = r.Register(ToolEntry{Name: "g1", Toolset: "git", Handler: noopHandler})
|
||||
_ = r.Register(ToolEntry{Name: "u1", Toolset: "", Handler: noopHandler}) // ungrouped
|
||||
|
||||
t.Run("filters by toolset", func(t *testing.T) {
|
||||
file := r.ByToolset("file")
|
||||
if len(file) != 2 {
|
||||
t.Errorf("expected 2 file tools, got %d", len(file))
|
||||
}
|
||||
names := toolNames(file)
|
||||
slices.Sort(names)
|
||||
if names[0] != "f1" || names[1] != "f2" {
|
||||
t.Errorf("unexpected names: %v", names)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("no match returns empty", func(t *testing.T) {
|
||||
none := r.ByToolset("nonexistent")
|
||||
if len(none) != 0 {
|
||||
t.Errorf("expected 0 tools, got %d", len(none))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty toolset matches ungrouped", func(t *testing.T) {
|
||||
ungrouped := r.ByToolset("")
|
||||
if len(ungrouped) != 1 {
|
||||
t.Errorf("expected 1 ungrouped tool, got %d", len(ungrouped))
|
||||
}
|
||||
if ungrouped[0].Name != "u1" {
|
||||
t.Errorf("unexpected name: %q", ungrouped[0].Name)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRegistryAvailable(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
_ = r.Register(ToolEntry{Name: "always", Handler: noopHandler})
|
||||
_ = r.Register(ToolEntry{Name: "offline", Handler: noopHandler, CheckFn: func() bool { return false }})
|
||||
_ = r.Register(ToolEntry{Name: "conditional", Handler: noopHandler, CheckFn: func() bool { return true }})
|
||||
|
||||
t.Run("returns only available tools", func(t *testing.T) {
|
||||
avail := r.Available()
|
||||
names := toolNames(avail)
|
||||
if !slices.Contains(names, "always") {
|
||||
t.Error("'always' should be available")
|
||||
}
|
||||
if !slices.Contains(names, "conditional") {
|
||||
t.Error("'conditional' should be available")
|
||||
}
|
||||
if slices.Contains(names, "offline") {
|
||||
t.Error("'offline' should not be available")
|
||||
}
|
||||
if len(avail) != 2 {
|
||||
t.Errorf("expected 2 available tools, got %d", len(avail))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("dynamic availability reflected", func(t *testing.T) {
|
||||
flag := true
|
||||
_ = r.Register(ToolEntry{
|
||||
Name: "toggle",
|
||||
Handler: noopHandler,
|
||||
CheckFn: func() bool { return flag },
|
||||
})
|
||||
if len(r.Available()) != 3 {
|
||||
t.Errorf("expected 3 available (toggle is true), got %d", len(r.Available()))
|
||||
}
|
||||
flag = false
|
||||
// Available() re-evaluates -- the closure captures &flag.
|
||||
if len(r.Available()) != 2 {
|
||||
t.Errorf("expected 2 available (toggle is now false), got %d", len(r.Available()))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// toolNames extracts names from a slice of ToolEntry.
|
||||
func toolNames(entries []ToolEntry) []string {
|
||||
names := make([]string, len(entries))
|
||||
for i, e := range entries {
|
||||
names[i] = e.Name
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func TestRegistryAvailableReentrySafety(t *testing.T) {
|
||||
// Regression: Available() called CheckFn while holding RLock,
|
||||
// which could deadlock if CheckFn re-entered the registry.
|
||||
// After the fix, CheckFn is evaluated outside the lock, so
|
||||
// calling All(), ByToolset(), or even Register() from inside
|
||||
// CheckFn cannot deadlock.
|
||||
r := NewRegistry()
|
||||
_ = r.Register(ToolEntry{Name: "safe", Handler: noopHandler})
|
||||
|
||||
called := false
|
||||
_ = r.Register(ToolEntry{
|
||||
Name: "reentrant",
|
||||
Handler: noopHandler,
|
||||
CheckFn: func() bool {
|
||||
called = true
|
||||
// Call All() from inside CheckFn -- must not deadlock.
|
||||
_ = r.All()
|
||||
// Call ByToolset from inside CheckFn -- must not deadlock.
|
||||
_ = r.ByToolset("")
|
||||
// Call Register from inside CheckFn -- must not deadlock
|
||||
// (was the original deadlock trigger when lock was held).
|
||||
_ = r.Register(ToolEntry{Name: "nested-reg", Handler: noopHandler})
|
||||
return true
|
||||
},
|
||||
})
|
||||
|
||||
avail := r.Available()
|
||||
if !called {
|
||||
t.Error("CheckFn was not called")
|
||||
}
|
||||
names := toolNames(avail)
|
||||
if !slices.Contains(names, "reentrant") {
|
||||
t.Error("reentrant tool should be available")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryRegisterDefensiveCopy(t *testing.T) {
|
||||
// Regression: Register() stored the caller's Schema map and
|
||||
// RequiresEnv slice without deep-copying, enabling data races.
|
||||
r := NewRegistry()
|
||||
|
||||
schema := JSONSchema{"key": "original"}
|
||||
env := []string{"ORIGINAL"}
|
||||
e := ToolEntry{Name: "copy-test", Handler: noopHandler, Schema: schema, RequiresEnv: env}
|
||||
|
||||
if err := r.Register(e); err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
|
||||
// Mutate the original schema and env -- must not affect registry.
|
||||
schema["key"] = "mutated"
|
||||
env[0] = "MUTATED"
|
||||
|
||||
all := r.All()
|
||||
if len(all) != 1 {
|
||||
t.Fatalf("expected 1 tool, got %d", len(all))
|
||||
}
|
||||
if all[0].Schema["key"] != "original" {
|
||||
t.Errorf("Schema[key] = %v, want 'original' -- caller mutation leaked into registry", all[0].Schema["key"])
|
||||
}
|
||||
if all[0].RequiresEnv[0] != "ORIGINAL" {
|
||||
t.Errorf("RequiresEnv[0] = %q, want 'ORIGINAL' -- caller mutation leaked into registry", all[0].RequiresEnv[0])
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure registry implements basic sanity at the package level.
|
||||
func TestRegistryPackageLevelHelpers(t *testing.T) {
|
||||
t.Run("Register and All via package helpers", func(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
e := ToolEntry{Name: "pkg_helper", Handler: noopHandler}
|
||||
if err := r.Register(e); err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
if len(r.All()) != 1 {
|
||||
t.Error("expected 1 tool after register")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ByToolset from empty reg", func(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
got := r.ByToolset("none")
|
||||
if len(got) != 0 {
|
||||
t.Errorf("expected 0, got %d", len(got))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Available from empty reg", func(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
got := r.Available()
|
||||
if len(got) != 0 {
|
||||
t.Errorf("expected 0, got %d", len(got))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRegistryRegisterBatchIsAtomic(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
existing []ToolEntry
|
||||
batch []ToolEntry
|
||||
wantErr bool
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "registers complete batch",
|
||||
batch: []ToolEntry{
|
||||
{Name: "one", Handler: noopHandler},
|
||||
{Name: "two", Handler: noopHandler},
|
||||
},
|
||||
want: []string{"one", "two"},
|
||||
},
|
||||
{
|
||||
name: "existing collision registers nothing",
|
||||
existing: []ToolEntry{{Name: "taken", Handler: noopHandler}},
|
||||
batch: []ToolEntry{
|
||||
{Name: "new", Handler: noopHandler},
|
||||
{Name: "taken", Handler: noopHandler},
|
||||
},
|
||||
wantErr: true,
|
||||
want: []string{"taken"},
|
||||
},
|
||||
{
|
||||
name: "duplicate inside batch registers nothing",
|
||||
batch: []ToolEntry{
|
||||
{Name: "same", Handler: noopHandler},
|
||||
{Name: "same", Handler: noopHandler},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "invalid entry registers nothing",
|
||||
batch: []ToolEntry{
|
||||
{Name: "valid", Handler: noopHandler},
|
||||
{Name: "invalid"},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
registry := NewRegistry()
|
||||
for _, entry := range tt.existing {
|
||||
if err := registry.Register(entry); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
err := registry.RegisterBatch(tt.batch)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("RegisterBatch() error = %v, wantErr %t", err, tt.wantErr)
|
||||
}
|
||||
got := make([]string, 0, len(registry.All()))
|
||||
for _, entry := range registry.All() {
|
||||
got = append(got, entry.Name)
|
||||
}
|
||||
slices.Sort(got)
|
||||
if !slices.Equal(got, tt.want) {
|
||||
t.Fatalf("registered names = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryUnregister(t *testing.T) {
|
||||
registry := NewRegistry()
|
||||
for _, name := range []string{"keep", "remove"} {
|
||||
if err := registry.Register(ToolEntry{Name: name, Handler: noopHandler}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
registry.Unregister("remove", "unknown")
|
||||
|
||||
if _, ok := registry.Get("remove"); ok {
|
||||
t.Fatal("removed tool remains registered")
|
||||
}
|
||||
if _, ok := registry.Get("keep"); !ok {
|
||||
t.Fatal("unrelated tool was removed")
|
||||
}
|
||||
}
|
||||
@@ -1,224 +0,0 @@
|
||||
package sendfile
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
"github.com/samcharles93/archie-core/internal/tools/builtin"
|
||||
)
|
||||
|
||||
// writeFile creates a file of size bytes under dir and returns its path.
|
||||
func writeFile(t *testing.T, dir, name string, size int) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(dir, name)
|
||||
if err := os.WriteFile(path, make([]byte, size), 0o600); err != nil {
|
||||
t.Fatalf("write %s: %v", path, err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// A prepared send must name the file as a local Path, never as a URL:
|
||||
// upload is the whole point, and a path in the URL field is exactly the
|
||||
// silent non-delivery this tool exists to end.
|
||||
func TestPrepareReturnsLocalPathRef(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
file string
|
||||
wantType string
|
||||
}{
|
||||
{"markdown is a document", "transcript.md", "document"},
|
||||
{"unknown extension is a document", "dump.bin", "document"},
|
||||
{"png is an image", "shot.png", "image"},
|
||||
{"jpeg is an image", "photo.jpg", "image"},
|
||||
// An svg IS an image, but no photo endpoint accepts one, so
|
||||
// calling it one turns a deliverable file into a failed send.
|
||||
{"svg is a document, not a photo", "diagram.svg", "document"},
|
||||
{"tiff is a document, not a photo", "scan.tiff", "document"},
|
||||
{"mp4 is a video", "clip.mp4", "video"},
|
||||
{"mp3 is audio", "note.mp3", "audio"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ws := t.TempDir()
|
||||
path := writeFile(t, ws, tc.file, 16)
|
||||
|
||||
// Relative, to prove resolution happens against the workspace.
|
||||
res, err := prepare(ws, tc.file, "here you go")
|
||||
if err != nil {
|
||||
t.Fatalf("prepare: %v", err)
|
||||
}
|
||||
if !res.IsMultimodal {
|
||||
t.Error("IsMultimodal = false, want true")
|
||||
}
|
||||
if len(res.URLs) != 1 {
|
||||
t.Fatalf("refs = %d, want 1", len(res.URLs))
|
||||
}
|
||||
ref := res.URLs[0]
|
||||
if ref.Path != path {
|
||||
t.Errorf("Path = %q, want %q", ref.Path, path)
|
||||
}
|
||||
if ref.URL != "" {
|
||||
t.Errorf("URL = %q, want empty: a local file has no URL", ref.URL)
|
||||
}
|
||||
if ref.FileName != tc.file {
|
||||
t.Errorf("FileName = %q, want %q", ref.FileName, tc.file)
|
||||
}
|
||||
if ref.Type != tc.wantType {
|
||||
t.Errorf("Type = %q, want %q", ref.Type, tc.wantType)
|
||||
}
|
||||
if !strings.Contains(res.Summary, "here you go") {
|
||||
t.Errorf("Summary = %q, want it to carry the caption", res.Summary)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Every failure must be an error the model sees. Reporting a
|
||||
// MultimodalResult for a file that cannot be delivered would put the
|
||||
// caller back where it started: unable to tell delivery from silence.
|
||||
func TestPrepareFailuresAreErrors(t *testing.T) {
|
||||
ws := t.TempDir()
|
||||
outside := t.TempDir()
|
||||
writeFile(t, outside, "secret.txt", 8)
|
||||
locked := writeFile(t, ws, "locked.txt", 8)
|
||||
if err := os.Chmod(locked, 0o000); err != nil {
|
||||
t.Fatalf("chmod: %v", err)
|
||||
}
|
||||
if os.Geteuid() == 0 {
|
||||
// root ignores the mode bits, so the probe cannot fail this way.
|
||||
t.Skip("running as root: an unreadable file is still readable")
|
||||
}
|
||||
big := writeFile(t, ws, "big.bin", 0)
|
||||
if err := os.Truncate(big, MaxUploadBytes+1); err != nil {
|
||||
t.Fatalf("truncate: %v", err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
path string
|
||||
wantErr error
|
||||
wantSub string
|
||||
}{
|
||||
{name: "empty path", path: " ", wantSub: "path is required"},
|
||||
{name: "missing file", path: "nope.txt", wantErr: os.ErrNotExist},
|
||||
{name: "directory", path: ".", wantSub: "not a regular file"},
|
||||
{name: "unreadable file", path: "locked.txt", wantErr: os.ErrPermission},
|
||||
{name: "over the upload limit", path: "big.bin", wantSub: "upload limit"},
|
||||
{
|
||||
name: "outside the workspace",
|
||||
path: filepath.Join(outside, "secret.txt"),
|
||||
wantErr: builtin.ErrPathNotAllowed,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
res, err := prepare(ws, tc.path, "")
|
||||
if err == nil {
|
||||
t.Fatalf("prepare succeeded, want an error (got %+v)", res)
|
||||
}
|
||||
if len(res.URLs) != 0 || res.IsMultimodal {
|
||||
t.Errorf("failed prepare returned deliverable media: %+v", res)
|
||||
}
|
||||
if tc.wantErr != nil && !errors.Is(err, tc.wantErr) {
|
||||
t.Errorf("err = %v, want it to wrap %v", err, tc.wantErr)
|
||||
}
|
||||
if tc.wantSub != "" && !strings.Contains(err.Error(), tc.wantSub) {
|
||||
t.Errorf("err = %v, want it to mention %q", err, tc.wantSub)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An image is capped far lower than everything else by the platform that
|
||||
// delivers it. Checking one 50 MB ceiling for every type told the model an
|
||||
// 11 MB screenshot was sent and left the rejection to a layer it cannot
|
||||
// see -- the early check has to be the check that actually applies.
|
||||
func TestPrepareAppliesTheImageLimit(t *testing.T) {
|
||||
ws := t.TempDir()
|
||||
png := writeFile(t, ws, "shot.png", 0)
|
||||
if err := os.Truncate(png, MaxImageUploadBytes+1); err != nil {
|
||||
t.Fatalf("truncate: %v", err)
|
||||
}
|
||||
if _, err := prepare(ws, "shot.png", ""); err == nil ||
|
||||
!strings.Contains(err.Error(), "upload limit") {
|
||||
t.Fatalf("err = %v, want an over-the-image-limit error", err)
|
||||
}
|
||||
|
||||
// The same size as a document is fine: the limits must stay
|
||||
// per-type rather than collapsing into one conservative number.
|
||||
doc := writeFile(t, ws, "dump.bin", 0)
|
||||
if err := os.Truncate(doc, MaxImageUploadBytes+1); err != nil {
|
||||
t.Fatalf("truncate: %v", err)
|
||||
}
|
||||
if _, err := prepare(ws, "dump.bin", ""); err != nil {
|
||||
t.Fatalf("prepare document of image-limit+1 bytes: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Confinement is a deployment posture: with the jail lifted, a path
|
||||
// outside the workspace must be sendable, exactly as the read tool can
|
||||
// read it.
|
||||
func TestPrepareRespectsUnrestrictedFilesystem(t *testing.T) {
|
||||
ws := t.TempDir()
|
||||
outside := t.TempDir()
|
||||
path := writeFile(t, outside, "unit.service", 8)
|
||||
|
||||
if _, err := prepare(ws, path, ""); !errors.Is(err, builtin.ErrPathNotAllowed) {
|
||||
t.Fatalf("err = %v, want ErrPathNotAllowed while confined", err)
|
||||
}
|
||||
|
||||
builtin.SetPathConfinement(false)
|
||||
t.Cleanup(func() { builtin.SetPathConfinement(true) })
|
||||
|
||||
res, err := prepare(ws, path, "")
|
||||
if err != nil {
|
||||
t.Fatalf("prepare with confinement lifted: %v", err)
|
||||
}
|
||||
if len(res.URLs) != 1 || res.URLs[0].Path != path {
|
||||
t.Fatalf("refs = %+v, want the outside path", res.URLs)
|
||||
}
|
||||
}
|
||||
|
||||
// The entry withdraws entirely without a workspace: there is no root to
|
||||
// resolve against and no policy to apply.
|
||||
func TestToolRequiresWorkspace(t *testing.T) {
|
||||
if entry := Tool(""); entry != nil {
|
||||
t.Fatalf("Tool(\"\") = %+v, want nil", entry)
|
||||
}
|
||||
entry := Tool(t.TempDir())
|
||||
if entry == nil {
|
||||
t.Fatal("Tool(workspace) = nil, want an entry")
|
||||
}
|
||||
if entry.Name != ToolName {
|
||||
t.Errorf("Name = %q, want %q", entry.Name, ToolName)
|
||||
}
|
||||
if entry.Handler == nil {
|
||||
t.Error("Handler is nil")
|
||||
}
|
||||
}
|
||||
|
||||
// The handler must return the same result shape the channel decodes, so a
|
||||
// wiring change cannot quietly stop producing media refs.
|
||||
func TestHandlerReturnsMultimodalResult(t *testing.T) {
|
||||
ws := t.TempDir()
|
||||
writeFile(t, ws, "log.txt", 4)
|
||||
entry := Tool(ws)
|
||||
|
||||
out, err := entry.Handler(t.Context(), map[string]any{"path": "log.txt"})
|
||||
if err != nil {
|
||||
t.Fatalf("handler: %v", err)
|
||||
}
|
||||
res, ok := out.(tools.MultimodalResult)
|
||||
if !ok {
|
||||
t.Fatalf("out is %T, want tools.MultimodalResult", out)
|
||||
}
|
||||
if len(res.URLs) != 1 {
|
||||
t.Fatalf("refs = %d, want 1", len(res.URLs))
|
||||
}
|
||||
}
|
||||
@@ -1,358 +0,0 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"maps"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// noopHandler is a Handler that does nothing.
|
||||
func noopHandler(_ context.Context, _ map[string]any) (any, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// echoHandler returns its input unchanged.
|
||||
func echoHandler(_ context.Context, in map[string]any) (any, error) {
|
||||
return in, nil
|
||||
}
|
||||
|
||||
func TestToolEntryValidate(t *testing.T) {
|
||||
t.Run("valid entry", func(t *testing.T) {
|
||||
e := ToolEntry{Name: "hello", Handler: noopHandler}
|
||||
if err := e.Validate(); err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("missing name", func(t *testing.T) {
|
||||
e := ToolEntry{Handler: noopHandler}
|
||||
if err := e.Validate(); err == nil {
|
||||
t.Error("expected error for missing name")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("missing handler", func(t *testing.T) {
|
||||
e := ToolEntry{Name: "orphan"}
|
||||
if err := e.Validate(); err == nil {
|
||||
t.Error("expected error for missing handler")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestToolEntryAvailable(t *testing.T) {
|
||||
t.Run("nil CheckFn is always available", func(t *testing.T) {
|
||||
e := ToolEntry{Name: "x", Handler: noopHandler}
|
||||
if !e.Available() {
|
||||
t.Error("nil CheckFn should mean available")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("CheckFn returning true", func(t *testing.T) {
|
||||
e := ToolEntry{
|
||||
Name: "x",
|
||||
Handler: noopHandler,
|
||||
CheckFn: func() bool { return true },
|
||||
}
|
||||
if !e.Available() {
|
||||
t.Error("expect available when CheckFn returns true")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("CheckFn returning false", func(t *testing.T) {
|
||||
e := ToolEntry{
|
||||
Name: "x",
|
||||
Handler: noopHandler,
|
||||
CheckFn: func() bool { return false },
|
||||
}
|
||||
if e.Available() {
|
||||
t.Error("expect unavailable when CheckFn returns false")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("CheckFn reflects dynamic state", func(t *testing.T) {
|
||||
flag := true
|
||||
e := ToolEntry{
|
||||
Name: "x",
|
||||
Handler: noopHandler,
|
||||
CheckFn: func() bool { return flag },
|
||||
}
|
||||
if !e.Available() {
|
||||
t.Error("expect available while flag is true")
|
||||
}
|
||||
flag = false
|
||||
if e.Available() {
|
||||
t.Error("expect unavailable after flag toggled")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestToolEntryResolvedSchema(t *testing.T) {
|
||||
t.Run("static schema returned as-is", func(t *testing.T) {
|
||||
e := ToolEntry{
|
||||
Name: "x",
|
||||
Handler: noopHandler,
|
||||
Schema: JSONSchema{"type": "object", "properties": JSONSchema{"x": JSONSchema{"type": "string"}}},
|
||||
}
|
||||
s := e.ResolvedSchema()
|
||||
if s["type"] != "object" {
|
||||
t.Errorf("type = %v", s["type"])
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("nil schema with no override", func(t *testing.T) {
|
||||
e := ToolEntry{Name: "x", Handler: noopHandler}
|
||||
if e.ResolvedSchema() != nil {
|
||||
t.Error("nil schema should stay nil")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("dynamic override injects values", func(t *testing.T) {
|
||||
e := ToolEntry{
|
||||
Name: "x",
|
||||
Handler: noopHandler,
|
||||
Schema: JSONSchema{"type": "object"},
|
||||
DynamicSchemaOverrides: func(s JSONSchema) JSONSchema {
|
||||
out := JSONSchema{}
|
||||
maps.Copy(out, s)
|
||||
out["dynamic"] = true
|
||||
return out
|
||||
},
|
||||
}
|
||||
s := e.ResolvedSchema()
|
||||
if s["dynamic"] != true {
|
||||
t.Error("dynamic override not applied")
|
||||
}
|
||||
// Original must be unchanged.
|
||||
if e.Schema["dynamic"] != nil {
|
||||
t.Error("override mutated original schema")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("override can return nil", func(t *testing.T) {
|
||||
e := ToolEntry{
|
||||
Name: "x",
|
||||
Handler: noopHandler,
|
||||
Schema: JSONSchema{"type": "object"},
|
||||
DynamicSchemaOverrides: func(_ JSONSchema) JSONSchema {
|
||||
return nil
|
||||
},
|
||||
}
|
||||
if e.ResolvedSchema() != nil {
|
||||
t.Error("override returning nil should be respected")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestToolEntryClone(t *testing.T) {
|
||||
e := ToolEntry{
|
||||
Name: "original",
|
||||
Toolset: "test",
|
||||
Schema: JSONSchema{"key": "value"},
|
||||
Handler: noopHandler,
|
||||
CheckFn: func() bool { return true },
|
||||
RequiresEnv: []string{"X", "Y"},
|
||||
IsAsync: true,
|
||||
Description: "a test tool",
|
||||
Emoji: "🧪",
|
||||
MaxResultSizeChars: 4096,
|
||||
}
|
||||
|
||||
clone := e.Clone()
|
||||
|
||||
// Value fields match.
|
||||
if clone.Name != e.Name {
|
||||
t.Errorf("Name = %q, want %q", clone.Name, e.Name)
|
||||
}
|
||||
if clone.IsAsync != e.IsAsync {
|
||||
t.Errorf("IsAsync = %v, want %v", clone.IsAsync, e.IsAsync)
|
||||
}
|
||||
|
||||
// Handler and CheckFn are shared (function pointers -- not deep-copied).
|
||||
// This is documented behavior.
|
||||
|
||||
// RequiresEnv is an independent copy.
|
||||
e.RequiresEnv[0] = "Z"
|
||||
if clone.RequiresEnv[0] != "X" {
|
||||
t.Errorf("RequiresEnv[0] = %q, want %q (clone should be independent)", clone.RequiresEnv[0], "X")
|
||||
}
|
||||
|
||||
// Schema is an independent deep copy.
|
||||
e.Schema["key"] = "mutated"
|
||||
if clone.Schema["key"] != "value" {
|
||||
t.Errorf("Schema[key] = %v, want 'value' (clone should be independent)", clone.Schema["key"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolEntryCloneDeepNested(t *testing.T) {
|
||||
// Regression: Clone() used maps.Copy which only does a shallow copy
|
||||
// of Schema values. Nested maps and slices were shared between
|
||||
// the clone and original, enabling mutation leaks.
|
||||
e := ToolEntry{
|
||||
Name: "nested",
|
||||
Handler: noopHandler,
|
||||
Schema: JSONSchema{
|
||||
"type": "object",
|
||||
"properties": JSONSchema{
|
||||
"name": JSONSchema{"type": "string"},
|
||||
},
|
||||
"required": []any{"name"},
|
||||
"tags": []string{"a", "b"},
|
||||
},
|
||||
}
|
||||
clone := e.Clone()
|
||||
|
||||
// Mutate nested map in original.
|
||||
props, ok := e.Schema["properties"].(JSONSchema)
|
||||
if !ok {
|
||||
t.Fatalf("e.Schema[\"properties\"] is %T, want JSONSchema", e.Schema["properties"])
|
||||
}
|
||||
props["name"] = JSONSchema{"type": "integer"}
|
||||
cloneProps, ok := clone.Schema["properties"].(JSONSchema)
|
||||
if !ok {
|
||||
t.Fatalf("clone.Schema[\"properties\"] is %T, want JSONSchema", clone.Schema["properties"])
|
||||
}
|
||||
clonePropName, ok := cloneProps["name"].(JSONSchema)
|
||||
if !ok {
|
||||
t.Fatalf("cloneProps[\"name\"] is %T, want JSONSchema", cloneProps["name"])
|
||||
}
|
||||
if clonePropName["type"] != "string" {
|
||||
t.Error("nested schema map mutation leaked into clone")
|
||||
}
|
||||
|
||||
// Mutate nested slice in original.
|
||||
req, ok := e.Schema["required"].([]any)
|
||||
if !ok {
|
||||
t.Fatalf("e.Schema[\"required\"] is %T, want []any", e.Schema["required"])
|
||||
}
|
||||
req[0] = "email"
|
||||
cloneReq, ok := clone.Schema["required"].([]any)
|
||||
if !ok {
|
||||
t.Fatalf("clone.Schema[\"required\"] is %T, want []any", clone.Schema["required"])
|
||||
}
|
||||
if cloneReq[0] != "name" {
|
||||
t.Error("nested schema []any slice mutation leaked into clone")
|
||||
}
|
||||
|
||||
// Mutate string slice in original.
|
||||
tags, ok := e.Schema["tags"].([]string)
|
||||
if !ok {
|
||||
t.Fatalf("e.Schema[\"tags\"] is %T, want []string", e.Schema["tags"])
|
||||
}
|
||||
tags[0] = "mutated"
|
||||
cloneTags, ok := clone.Schema["tags"].([]string)
|
||||
if !ok {
|
||||
t.Fatalf("clone.Schema[\"tags\"] is %T, want []string", clone.Schema["tags"])
|
||||
}
|
||||
if cloneTags[0] != "a" {
|
||||
t.Error("nested schema []string slice mutation leaked into clone")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolEntryJSONRoundTrip(t *testing.T) {
|
||||
e := ToolEntry{
|
||||
Name: "greet",
|
||||
Toolset: "demo",
|
||||
Schema: JSONSchema{"type": "object", "properties": JSONSchema{"name": JSONSchema{"type": "string"}}},
|
||||
Handler: noopHandler, // json:"-" -- excluded
|
||||
CheckFn: func() bool { return true }, // json:"-" -- excluded
|
||||
RequiresEnv: []string{"GREET_NAME"},
|
||||
IsAsync: true,
|
||||
Description: "Sends a greeting",
|
||||
Emoji: "👋",
|
||||
MaxResultSizeChars: 1000,
|
||||
DynamicSchemaOverrides: nil, // json:"-" -- excluded
|
||||
}
|
||||
|
||||
data, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
|
||||
// Round-trip.
|
||||
var decoded ToolEntry
|
||||
if err := json.Unmarshal(data, &decoded); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
|
||||
if decoded.Name != "greet" {
|
||||
t.Errorf("Name = %q", decoded.Name)
|
||||
}
|
||||
if decoded.Toolset != "demo" {
|
||||
t.Errorf("Toolset = %q", decoded.Toolset)
|
||||
}
|
||||
if decoded.IsAsync != true {
|
||||
t.Error("IsAsync not preserved")
|
||||
}
|
||||
if decoded.Description != "Sends a greeting" {
|
||||
t.Errorf("Description = %q", decoded.Description)
|
||||
}
|
||||
if decoded.Emoji != "👋" {
|
||||
t.Errorf("Emoji = %q", decoded.Emoji)
|
||||
}
|
||||
if decoded.MaxResultSizeChars != 1000 {
|
||||
t.Errorf("MaxResultSizeChars = %d", decoded.MaxResultSizeChars)
|
||||
}
|
||||
if len(decoded.RequiresEnv) != 1 || decoded.RequiresEnv[0] != "GREET_NAME" {
|
||||
t.Errorf("RequiresEnv = %v", decoded.RequiresEnv)
|
||||
}
|
||||
|
||||
// Runtime fields are not deserialized.
|
||||
if decoded.Handler != nil {
|
||||
t.Error("Handler should be nil after unmarshal")
|
||||
}
|
||||
if decoded.CheckFn != nil {
|
||||
t.Error("CheckFn should be nil after unmarshal")
|
||||
}
|
||||
|
||||
// Schema survives round-trip.
|
||||
if decoded.Schema["type"] != "object" {
|
||||
t.Errorf("Schema type = %v", decoded.Schema["type"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolEntryHandlerExecution(t *testing.T) {
|
||||
e := ToolEntry{
|
||||
Name: "echo",
|
||||
Handler: echoHandler,
|
||||
}
|
||||
|
||||
out, err := e.Handler(context.Background(), map[string]any{"msg": "hello"})
|
||||
if err != nil {
|
||||
t.Fatalf("handler error: %v", err)
|
||||
}
|
||||
m, ok := out.(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("expected map, got %T", out)
|
||||
}
|
||||
if m["msg"] != "hello" {
|
||||
t.Errorf("msg = %v", m["msg"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolEntryZeroValue(t *testing.T) {
|
||||
var e ToolEntry
|
||||
// Zero value must be usable without panicking.
|
||||
if err := e.Validate(); err == nil {
|
||||
t.Error("zero ToolEntry should fail Validate")
|
||||
}
|
||||
if !e.Available() {
|
||||
t.Error("zero ToolEntry should be Available (nil CheckFn = available)")
|
||||
}
|
||||
if e.ResolvedSchema() != nil {
|
||||
t.Error("zero ToolEntry should have nil resolved schema")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolEntryJSONSchemaIsNilByDefault(t *testing.T) {
|
||||
e := ToolEntry{Name: "no-params", Handler: noopHandler}
|
||||
data, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
// Schema field omitted when nil.
|
||||
if strings.Contains(string(data), `"schema"`) {
|
||||
t.Log("schema present in JSON (either null or omitted) -- both are acceptable")
|
||||
}
|
||||
}
|
||||
@@ -1,272 +0,0 @@
|
||||
package webfetch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// testConfig is the base every case starts from. Private networks are allowed
|
||||
// because httptest binds loopback; the cases that exercise the SSRF control
|
||||
// override it explicitly.
|
||||
func testConfig() Config {
|
||||
return Config{
|
||||
Enabled: true,
|
||||
Timeout: 5 * time.Second,
|
||||
MaxBytes: 1 << 20,
|
||||
AllowPrivateNetworks: true,
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchExtractsContent(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
contentType string
|
||||
body string
|
||||
raw bool
|
||||
wantContain []string
|
||||
wantAbsent []string
|
||||
}{
|
||||
{
|
||||
name: "html is reduced to readable text",
|
||||
contentType: "text/html; charset=utf-8",
|
||||
body: `<html><head><title>T</title>
|
||||
<style>body{color:red}</style>
|
||||
<script>var x = "should not appear";</script></head>
|
||||
<body><h1>Heading</h1><p>Body text here.</p></body></html>`,
|
||||
wantContain: []string{"Heading", "Body text here."},
|
||||
wantAbsent: []string{"should not appear", "color:red", "<p>"},
|
||||
},
|
||||
{
|
||||
name: "raw returns the html unmodified",
|
||||
contentType: "text/html",
|
||||
body: `<p>markup</p>`,
|
||||
raw: true,
|
||||
wantContain: []string{"<p>markup</p>"},
|
||||
},
|
||||
{
|
||||
name: "json passes through untouched",
|
||||
contentType: "application/json",
|
||||
body: `{"key":"value"}`,
|
||||
wantContain: []string{`{"key":"value"}`},
|
||||
},
|
||||
{
|
||||
name: "plain text passes through untouched",
|
||||
contentType: "text/plain",
|
||||
body: "just words",
|
||||
wantContain: []string{"just words"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", tc.contentType)
|
||||
fmt.Fprint(w, tc.body)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
got, err := New(testConfig()).Fetch(context.Background(), srv.URL, tc.raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, want := range tc.wantContain {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("result %q does not contain %q", got, want)
|
||||
}
|
||||
}
|
||||
for _, absent := range tc.wantAbsent {
|
||||
if strings.Contains(got, absent) {
|
||||
t.Errorf("result %q should not contain %q", got, absent)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchRejectsUnsupportedContentType(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
fmt.Fprint(w, "\x89PNG\r\n\x1a\n")
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
_, err := New(testConfig()).Fetch(context.Background(), srv.URL, false)
|
||||
if err == nil {
|
||||
t.Fatal("Fetch() error = nil, want a refusal naming the content type")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "image/png") {
|
||||
t.Errorf("error = %v, want it to name the content type", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchCapsBodySize(t *testing.T) {
|
||||
const limit = 512
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
fmt.Fprint(w, strings.Repeat("a", limit*10))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
cfg := testConfig()
|
||||
cfg.MaxBytes = limit
|
||||
got, err := New(cfg).Fetch(context.Background(), srv.URL, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) > limit*2 { // body plus a truncation notice, nowhere near 10x
|
||||
t.Errorf("result is %d bytes, want it bounded near the %d-byte limit", len(got), limit)
|
||||
}
|
||||
if !strings.Contains(got, "truncated") {
|
||||
t.Errorf("result %q should say it was truncated", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchReportsHTTPStatus(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
{name: "not found", status: http.StatusNotFound, body: "no such page"},
|
||||
{name: "forbidden", status: http.StatusForbidden, body: "denied"},
|
||||
{name: "rate limited", status: http.StatusTooManyRequests, body: "slow down"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
w.WriteHeader(tc.status)
|
||||
fmt.Fprint(w, tc.body)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
_, err := New(testConfig()).Fetch(context.Background(), srv.URL, false)
|
||||
if err == nil {
|
||||
t.Fatalf("Fetch() error = nil, want the %d reported", tc.status)
|
||||
}
|
||||
// The model has to tell 404 from 403 from a rate limit to decide
|
||||
// whether retrying or rewording the URL is worth it.
|
||||
if !strings.Contains(err.Error(), fmt.Sprint(tc.status)) {
|
||||
t.Errorf("error = %v, want it to carry status %d", err, tc.status)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tc.body) {
|
||||
t.Errorf("error = %v, want it to carry a body excerpt", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchCapsRedirects(t *testing.T) {
|
||||
var srv *httptest.Server
|
||||
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, srv.URL+"/next", http.StatusFound)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
_, err := New(testConfig()).Fetch(context.Background(), srv.URL, false)
|
||||
if err == nil {
|
||||
t.Fatal("Fetch() error = nil, want a redirect-limit refusal")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "redirect") {
|
||||
t.Errorf("error = %v, want it to name the redirect limit", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchRejectsUnsupportedSchemes(t *testing.T) {
|
||||
tests := []string{
|
||||
"file:///etc/passwd",
|
||||
"ftp://example.com/x",
|
||||
"gopher://example.com",
|
||||
"data:text/plain,hello",
|
||||
"not-a-url",
|
||||
}
|
||||
|
||||
for _, target := range tests {
|
||||
t.Run(target, func(t *testing.T) {
|
||||
_, err := New(testConfig()).Fetch(context.Background(), target, false)
|
||||
if err == nil {
|
||||
t.Fatalf("Fetch(%q) error = nil, want a scheme refusal", target)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFetchBlocksPrivateAddresses is the SSRF control. archied runs on a host
|
||||
// where the Docker API, NATS and its own dashboard are reachable on private
|
||||
// addresses, so a model that can be talked into fetching one of those is a
|
||||
// real hole. httptest binds loopback, which makes it exactly the case to
|
||||
// assert against.
|
||||
func TestFetchBlocksPrivateAddresses(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
fmt.Fprint(w, "internal service")
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
t.Run("blocked by default", func(t *testing.T) {
|
||||
cfg := testConfig()
|
||||
cfg.AllowPrivateNetworks = false
|
||||
_, err := New(cfg).Fetch(context.Background(), srv.URL, false)
|
||||
if err == nil {
|
||||
t.Fatal("Fetch() reached a loopback address, want a refusal")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "private") && !strings.Contains(err.Error(), "loopback") {
|
||||
t.Errorf("error = %v, want it to explain the address was refused", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("allowed when configured", func(t *testing.T) {
|
||||
cfg := testConfig() // AllowPrivateNetworks is true
|
||||
got, err := New(cfg).Fetch(context.Background(), srv.URL, false)
|
||||
if err != nil {
|
||||
t.Fatalf("Fetch() with private networks allowed: %v", err)
|
||||
}
|
||||
if !strings.Contains(got, "internal service") {
|
||||
t.Errorf("result = %q, want the body", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestFetchBlocksAtDialTime proves the check is on the resolved address rather
|
||||
// than on the URL string. A hostname that looks public but resolves to a
|
||||
// private address must still be refused, which a pre-flight URL check cannot
|
||||
// do and which is how DNS-rebinding defeats one.
|
||||
func TestFetchBlocksAtDialTime(t *testing.T) {
|
||||
cfg := testConfig()
|
||||
cfg.AllowPrivateNetworks = false
|
||||
|
||||
// localtest.me and its subdomains are a public DNS name resolving to
|
||||
// 127.0.0.1. Resolution may be unavailable in a sandbox, so a lookup
|
||||
// failure is not a test failure -- but a success must be a refusal.
|
||||
_, err := New(cfg).Fetch(context.Background(), "http://localtest.me/", false)
|
||||
if err == nil {
|
||||
t.Fatal("Fetch() reached a public name resolving to loopback, want a refusal")
|
||||
}
|
||||
if strings.Contains(err.Error(), "scheme") {
|
||||
t.Errorf("error = %v, want an address refusal rather than a scheme refusal", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolDisabledReturnsNil(t *testing.T) {
|
||||
cfg := testConfig()
|
||||
cfg.Enabled = false
|
||||
if Tool(cfg) != nil {
|
||||
t.Error("Tool() returned an entry while disabled, want nil so it is not advertised")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolRejectsMissingURL(t *testing.T) {
|
||||
entry := Tool(testConfig())
|
||||
if entry == nil {
|
||||
t.Fatal("Tool() = nil, want an entry when enabled")
|
||||
}
|
||||
if _, err := entry.Handler(context.Background(), map[string]any{}); err == nil {
|
||||
t.Error("Handler() error = nil, want a refusal when url is absent")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user