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,58 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The task-scoped archie-agent process owns the workflow and its local model
|
||||
// loop. agentexec therefore contains the worker-local stage runner, never a
|
||||
// second process boundary or a stage transport that archied can select.
|
||||
func TestPackageContainsNoLegacyExecutionModes(t *testing.T) {
|
||||
forbidden := map[string]bool{
|
||||
"InProcessRunner": true,
|
||||
"NewInProcessRunner": true,
|
||||
"SubprocessRunner": true,
|
||||
"NATSRunner": true,
|
||||
"ServeOne": true,
|
||||
"Invocation": true,
|
||||
"AgentRequestMessage": true,
|
||||
"AgentResponseEnvelope": true,
|
||||
"StageMessage": true,
|
||||
"StageConsumer": true,
|
||||
}
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fileset := token.NewFileSet()
|
||||
for _, path := range files {
|
||||
if strings.HasSuffix(path, "_test.go") {
|
||||
continue
|
||||
}
|
||||
file, parseErr := parser.ParseFile(fileset, path, nil, 0)
|
||||
if parseErr != nil {
|
||||
t.Errorf("parse %s: %v", path, parseErr)
|
||||
continue
|
||||
}
|
||||
for _, declaration := range file.Decls {
|
||||
switch declaration := declaration.(type) {
|
||||
case *ast.GenDecl:
|
||||
for _, spec := range declaration.Specs {
|
||||
typeSpec, ok := spec.(*ast.TypeSpec)
|
||||
if ok && forbidden[typeSpec.Name.Name] {
|
||||
t.Errorf("%s declares legacy execution type %s", fileset.Position(typeSpec.Pos()), typeSpec.Name.Name)
|
||||
}
|
||||
}
|
||||
case *ast.FuncDecl:
|
||||
if declaration.Recv == nil && forbidden[declaration.Name.Name] {
|
||||
t.Errorf("%s declares legacy execution constructor %s", fileset.Position(declaration.Pos()), declaration.Name.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
var findingTool = CaptureTool{
|
||||
Name: "record_finding",
|
||||
Description: "Record one finding.",
|
||||
Parameters: json.RawMessage(`{"type":"object","properties":{"title":{"type":"string"},"severity":{"type":"string"}},"required":["title"]}`),
|
||||
RequiredFields: []string{"title"},
|
||||
MaxCalls: 2,
|
||||
}
|
||||
|
||||
type lockedBuffer struct {
|
||||
mu sync.Mutex
|
||||
buf bytes.Buffer
|
||||
}
|
||||
|
||||
func (b *lockedBuffer) Write(p []byte) (int, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buf.Write(p)
|
||||
}
|
||||
|
||||
func (b *lockedBuffer) String() string {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buf.String()
|
||||
}
|
||||
|
||||
func connectCaptureServer(t *testing.T, sink *lockedBuffer) *mcp.ClientSession {
|
||||
t.Helper()
|
||||
serverT, clientT := mcp.NewInMemoryTransports()
|
||||
go func() { _ = ServeCaptureMCP(t.Context(), []CaptureTool{findingTool}, sink, serverT) }()
|
||||
session, err := mcp.NewClient(&mcp.Implementation{Name: "test", Version: "0"}, nil).Connect(t.Context(), clientT, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = session.Close() })
|
||||
return session
|
||||
}
|
||||
|
||||
func callText(t *testing.T, s *mcp.ClientSession, args any) string {
|
||||
t.Helper()
|
||||
res, err := s.CallTool(t.Context(), &mcp.CallToolParams{Name: "record_finding", Arguments: args})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out strings.Builder
|
||||
for _, c := range res.Content {
|
||||
if text, ok := c.(*mcp.TextContent); ok {
|
||||
out.WriteString(text.Text)
|
||||
}
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func TestCaptureMCPServesTheStageCaptureTools(t *testing.T) {
|
||||
sink := &lockedBuffer{}
|
||||
s := connectCaptureServer(t, sink)
|
||||
tools, err := s.ListTools(t.Context(), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(tools.Tools) != 1 || tools.Tools[0].Name != "record_finding" || tools.Tools[0].Description != "Record one finding." {
|
||||
t.Fatalf("tools %+v, want the stage's one capture tool", tools.Tools)
|
||||
}
|
||||
|
||||
if got := callText(t, s, map[string]any{"title": "nil deref", "severity": "important"}); !strings.Contains(got, "recorded") {
|
||||
t.Fatalf("valid call replied %q", got)
|
||||
}
|
||||
if got := callText(t, s, map[string]any{"severity": "nitpick"}); !strings.Contains(got, "rejected") {
|
||||
t.Fatalf("call missing a required field replied %q", got)
|
||||
}
|
||||
if got := callText(t, s, map[string]any{"title": "second"}); !strings.Contains(got, "recorded") {
|
||||
t.Fatalf("second valid call replied %q", got)
|
||||
}
|
||||
if got := callText(t, s, map[string]any{"title": "third"}); !strings.Contains(got, "maximum") {
|
||||
t.Fatalf("call past MaxCalls replied %q", got)
|
||||
}
|
||||
lines := strings.Split(strings.TrimSpace(sink.String()), "\n")
|
||||
if len(lines) != 2 {
|
||||
t.Fatalf("sink has %d records, want only the 2 accepted calls:\n%s", len(lines), sink.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadCapturesRevalidatesEverything(t *testing.T) {
|
||||
// The captures file is writable by the harness user, so anything in it
|
||||
// may be forged. Only records that pass the same validation survive.
|
||||
path := filepath.Join(t.TempDir(), "captures.jsonl")
|
||||
content := strings.Join([]string{
|
||||
`{"tool":"record_finding","args":{"title":"real"}}`,
|
||||
`{"tool":"record_finding","args":{"severity":"no title"}}`,
|
||||
`{"tool":"grant_admin","args":{"title":"x"}}`,
|
||||
`not json at all`,
|
||||
`{"tool":"record_finding","args":{"title":"second"}}`,
|
||||
`{"tool":"record_finding","args":{"title":"over the cap"}}`,
|
||||
}, "\n")
|
||||
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
captures, err := readCaptures(path, []CaptureTool{findingTool})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var titles []string
|
||||
for _, raw := range captures["record_finding"] {
|
||||
var v struct{ Title string }
|
||||
_ = json.Unmarshal(raw, &v)
|
||||
titles = append(titles, v.Title)
|
||||
}
|
||||
if !slices.Equal(titles, []string{"real", "second"}) || len(captures) != 1 {
|
||||
t.Fatalf("captures %v (titles %v), want only the two valid record_finding calls", captures, titles)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHarnessCollectsCapturesThroughTheMCPServer(t *testing.T) {
|
||||
f := newFixture(t, "capture")
|
||||
f.req.CaptureTools = []CaptureTool{findingTool}
|
||||
f.req.Harness.MCPConfig = []string{"--mcp-config", "{{.MCPConfig}}"}
|
||||
res, _ := f.run(t, t.Context())
|
||||
if res.Status != StatusPassed {
|
||||
t.Fatalf("status %q (%s)", res.Status, res.Detail)
|
||||
}
|
||||
if got := len(res.Captures["record_finding"]); got != 1 {
|
||||
t.Fatalf("captures %v, want the one valid record the harness made", res.Captures)
|
||||
}
|
||||
inv := f.invocations(t)
|
||||
if len(inv) != 1 || !strings.Contains(inv[0], "--mcp-config ") {
|
||||
t.Fatalf("invocations %q, want the MCP config registered", inv)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHarnessRefusesCaptureToolsWithoutMCP(t *testing.T) {
|
||||
f := newFixture(t, "edit")
|
||||
f.req.CaptureTools = []CaptureTool{findingTool}
|
||||
if _, err := NewHarnessRunner(nil).Run(t.Context(), f.workspace, f.req, nil); err == nil {
|
||||
t.Fatal("a stage with capture tools ran on a harness with no MCP registration; its results would be lost")
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A capture tool sometimes needs a field only under a condition the same call
|
||||
// carries: triage must name a workflow when it says a code change is needed,
|
||||
// and must not be made to invent one when it says the opposite. A flat
|
||||
// RequiredFields entry cannot say that, so the choice used to be between a
|
||||
// meaningless forced answer and a silent default.
|
||||
func TestValidateCaptureArgsConditionalRequirement(t *testing.T) {
|
||||
spec := CaptureTool{
|
||||
Name: "decide",
|
||||
RequiredFields: []string{"needs_code_change"},
|
||||
RequiredWhenTrue: map[string][]string{
|
||||
"needs_code_change": {"workflow"},
|
||||
},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
args string
|
||||
wantOK bool
|
||||
wantRejected string
|
||||
}{
|
||||
{
|
||||
name: "trigger true and field present",
|
||||
args: `{"needs_code_change": true, "workflow": "feasibility"}`,
|
||||
wantOK: true,
|
||||
},
|
||||
{
|
||||
name: "trigger true and field missing",
|
||||
args: `{"needs_code_change": true}`,
|
||||
wantRejected: "workflow",
|
||||
},
|
||||
{
|
||||
name: "trigger true and field empty",
|
||||
args: `{"needs_code_change": true, "workflow": " "}`,
|
||||
wantRejected: "workflow",
|
||||
},
|
||||
{
|
||||
name: "trigger false, field not required",
|
||||
args: `{"needs_code_change": false}`,
|
||||
wantOK: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
rejection, ok := validateCaptureArgs(spec, json.RawMessage(tt.args))
|
||||
if ok != tt.wantOK {
|
||||
t.Fatalf("validateCaptureArgs ok = %v, want %v (rejection %q)", ok, tt.wantOK, rejection)
|
||||
}
|
||||
if tt.wantRejected != "" && !strings.Contains(rejection, tt.wantRejected) {
|
||||
t.Fatalf("rejection %q does not name %q", rejection, tt.wantRejected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestClaudeCodeHarnessOutputFixtures(t *testing.T) {
|
||||
errorDetail := "Exit code 1\ncat: /nonexistent-file: No such file or directory"
|
||||
cases := []struct {
|
||||
name string
|
||||
wantCalls []ToolCallReport
|
||||
wantUsage Usage
|
||||
wantSession string
|
||||
}{
|
||||
{
|
||||
name: "run.jsonl",
|
||||
wantCalls: []ToolCallReport{
|
||||
{Tool: "Bash", Detail: "hello"},
|
||||
{Tool: "Bash", Detail: errorDetail, Failed: true},
|
||||
},
|
||||
wantUsage: Usage{PromptTokens: 102420, CompletionTokens: 248, TotalTokens: 102668, CachedTokens: 78105, CacheCreationTokens: 24309},
|
||||
wantSession: "9c22c15c-80ef-42c6-a503-8d087ec47d92",
|
||||
},
|
||||
{
|
||||
name: "killed-before-result.jsonl",
|
||||
wantCalls: []ToolCallReport{
|
||||
{Tool: "Bash", Detail: "hello"},
|
||||
{Tool: "Bash", Detail: errorDetail, Failed: true},
|
||||
},
|
||||
wantUsage: Usage{PromptTokens: 102420, CompletionTokens: 121, TotalTokens: 102541, CachedTokens: 78105, CacheCreationTokens: 24309},
|
||||
wantSession: "9c22c15c-80ef-42c6-a503-8d087ec47d92",
|
||||
},
|
||||
{
|
||||
name: "malformed-line.jsonl",
|
||||
wantCalls: []ToolCallReport{
|
||||
{Tool: "Bash", Detail: "hello"},
|
||||
{Tool: "Bash", Detail: errorDetail, Failed: true},
|
||||
},
|
||||
wantUsage: Usage{PromptTokens: 102420, CompletionTokens: 248, TotalTokens: 102668, CachedTokens: 78105, CacheCreationTokens: 24309},
|
||||
wantSession: "9c22c15c-80ef-42c6-a503-8d087ec47d92",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
stream, err := os.Open("testdata/claude/" + tc.name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer stream.Close()
|
||||
|
||||
output := newClaudeCodeHarnessOutput()
|
||||
var calls []ToolCallReport
|
||||
scanner := bufio.NewScanner(stream)
|
||||
for scanner.Scan() {
|
||||
output.Line(scanner.Bytes(), func(call ToolCallReport) { calls = append(calls, call) })
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(calls, tc.wantCalls) {
|
||||
t.Errorf("tool calls = %#v, want %#v", calls, tc.wantCalls)
|
||||
}
|
||||
if got := output.SessionID(); got != tc.wantSession {
|
||||
t.Errorf("session ID = %q, want %q", got, tc.wantSession)
|
||||
}
|
||||
if got := output.Usage(); got != tc.wantUsage {
|
||||
t.Errorf("usage = %#v, want %#v", got, tc.wantUsage)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaudeCodeHarnessOutputToolResultContent(t *testing.T) {
|
||||
long := strings.Repeat("x", toolCallDetailBytes+25)
|
||||
cases := []struct {
|
||||
name string
|
||||
content any
|
||||
wantDetail string
|
||||
}{
|
||||
{name: "string", content: "plain result", wantDetail: "plain result"},
|
||||
{name: "text blocks", content: []map[string]string{{"type": "text", "text": "first"}, {"type": "text", "text": "second"}}, wantDetail: "first\nsecond"},
|
||||
{name: "clipped", content: long, wantDetail: strings.Repeat("x", toolCallDetailBytes) + "…"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
output := newClaudeCodeHarnessOutput()
|
||||
var calls []ToolCallReport
|
||||
report := func(call ToolCallReport) { calls = append(calls, call) }
|
||||
sendClaudeEvent(t, output, report, map[string]any{
|
||||
"type": "assistant", "session_id": "old-session",
|
||||
"message": map[string]any{
|
||||
"id": "same-message", "usage": claudeUsageFixture(2, 3, 5, 7),
|
||||
"content": []any{map[string]any{"type": "tool_use", "id": "call-1", "name": "Read", "input": map[string]any{}}},
|
||||
},
|
||||
})
|
||||
sendClaudeEvent(t, output, report, map[string]any{
|
||||
"type": "assistant", "session_id": "newer-session",
|
||||
"message": map[string]any{
|
||||
"id": "same-message", "usage": claudeUsageFixture(2, 3, 5, 7),
|
||||
"content": []any{map[string]any{"type": "tool_use", "id": "call-2", "name": "Write", "input": map[string]any{}}},
|
||||
},
|
||||
})
|
||||
sendClaudeEvent(t, output, report, map[string]any{
|
||||
"type": "user", "session_id": "latest-session",
|
||||
"message": map[string]any{"content": []any{map[string]any{"type": "tool_result", "tool_use_id": "call-1", "content": tc.content, "is_error": false}}},
|
||||
})
|
||||
sendClaudeEvent(t, output, report, map[string]any{
|
||||
"type": "user", "session_id": "",
|
||||
"message": map[string]any{"content": []any{map[string]any{"type": "tool_result", "tool_use_id": "call-2", "content": "done", "is_error": false}}},
|
||||
})
|
||||
|
||||
wantCalls := []ToolCallReport{{Tool: "Read", Detail: tc.wantDetail}, {Tool: "Write", Detail: "done"}}
|
||||
if !reflect.DeepEqual(calls, wantCalls) {
|
||||
t.Errorf("tool calls = %#v, want %#v", calls, wantCalls)
|
||||
}
|
||||
wantUsage := Usage{PromptTokens: 14, CompletionTokens: 3, TotalTokens: 17, CachedTokens: 5, CacheCreationTokens: 7}
|
||||
if got := output.Usage(); got != wantUsage {
|
||||
t.Errorf("usage = %#v, want %#v", got, wantUsage)
|
||||
}
|
||||
if got := output.SessionID(); got != "latest-session" {
|
||||
t.Errorf("session ID = %q, want latest non-empty event value", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func sendClaudeEvent(t *testing.T, output HarnessOutput, report ToolCallReporter, event map[string]any) {
|
||||
t.Helper()
|
||||
line, err := json.Marshal(event)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output.Line(line, report)
|
||||
}
|
||||
|
||||
func claudeUsageFixture(input, output, cacheRead, cacheCreate int) map[string]any {
|
||||
return map[string]any{
|
||||
"input_tokens": input, "output_tokens": output,
|
||||
"cache_read_input_tokens": cacheRead, "cache_creation_input_tokens": cacheCreate,
|
||||
}
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHarnessOutputFixtures(t *testing.T) {
|
||||
const missing = "cat: /nonexistent-file: No such file or directory\n"
|
||||
cases := []struct {
|
||||
adapter string
|
||||
fixture string
|
||||
// stopAt truncates the stream before the first line containing it,
|
||||
// as when the process is killed mid-run.
|
||||
stopAt string
|
||||
wantCalls []ToolCallReport
|
||||
wantUsage Usage
|
||||
wantSession string
|
||||
}{
|
||||
{
|
||||
adapter: AdapterCodex, fixture: "codex/run.jsonl",
|
||||
wantCalls: []ToolCallReport{
|
||||
{Tool: "command_execution", Detail: "hello\n"},
|
||||
{Tool: "command_execution", Detail: missing, Failed: true},
|
||||
},
|
||||
wantUsage: Usage{PromptTokens: 72082, CompletionTokens: 118, TotalTokens: 72200, CachedTokens: 57600},
|
||||
wantSession: "01a0db18-e119-7872-bf13-3644369044fb",
|
||||
},
|
||||
{
|
||||
adapter: AdapterCodex, fixture: "codex/mcp.jsonl",
|
||||
wantCalls: []ToolCallReport{
|
||||
{Tool: "record_verdict", Detail: "record_verdict recorded"},
|
||||
{Tool: "file_change", Detail: "/tmp/hfx/note.txt"},
|
||||
},
|
||||
wantUsage: Usage{PromptTokens: 96397, CompletionTokens: 203, TotalTokens: 96600, CachedTokens: 80896},
|
||||
wantSession: "01a0db19-f9d6-7ad2-870c-c29b7fd8ab0a",
|
||||
},
|
||||
{
|
||||
adapter: AdapterCodex, fixture: "codex/run.jsonl", stopAt: `"turn.completed"`,
|
||||
wantCalls: []ToolCallReport{
|
||||
{Tool: "command_execution", Detail: "hello\n"},
|
||||
{Tool: "command_execution", Detail: missing, Failed: true},
|
||||
},
|
||||
wantSession: "01a0db18-e119-7872-bf13-3644369044fb",
|
||||
},
|
||||
{
|
||||
adapter: AdapterPi, fixture: "pi/run.jsonl",
|
||||
wantCalls: []ToolCallReport{
|
||||
{Tool: "bash", Detail: "hello\n"},
|
||||
{Tool: "bash", Detail: missing + "\n\nCommand exited with code 1", Failed: true},
|
||||
},
|
||||
wantUsage: Usage{PromptTokens: 109198, CompletionTokens: 38, TotalTokens: 109236, CachedTokens: 62720},
|
||||
wantSession: "01a0db18-e183-7432-9e4b-4b16bfc83856",
|
||||
},
|
||||
{
|
||||
adapter: AdapterPi, fixture: "pi/run.jsonl", stopAt: `"agent_end"`,
|
||||
wantCalls: []ToolCallReport{
|
||||
{Tool: "bash", Detail: "hello\n"},
|
||||
{Tool: "bash", Detail: missing + "\n\nCommand exited with code 1", Failed: true},
|
||||
},
|
||||
wantUsage: Usage{PromptTokens: 109198, CompletionTokens: 38, TotalTokens: 109236, CachedTokens: 62720},
|
||||
wantSession: "01a0db18-e183-7432-9e4b-4b16bfc83856",
|
||||
},
|
||||
{
|
||||
adapter: AdapterOMP, fixture: "omp/run.jsonl",
|
||||
wantCalls: []ToolCallReport{
|
||||
{Tool: "bash", Detail: "hello\n\n\nWall time: 0.03 seconds"},
|
||||
{Tool: "bash", Detail: missing + "\n\nWall time: 0.00 seconds\n\nCommand exited with code 1", Failed: true},
|
||||
},
|
||||
wantUsage: Usage{PromptTokens: 75962, CompletionTokens: 161, TotalTokens: 76123, CachedTokens: 50304},
|
||||
wantSession: "01a0db18-e4a1-7000-9cbe-7467b0385e65",
|
||||
},
|
||||
{
|
||||
adapter: AdapterCopilot, fixture: "copilot/run.jsonl",
|
||||
wantCalls: []ToolCallReport{
|
||||
{Tool: "bash", Detail: "hello\n<shellId: 0 completed with exit code 0>"},
|
||||
{Tool: "bash", Detail: missing + "<shellId: 1 completed with exit code 1>"},
|
||||
},
|
||||
wantSession: "bdf5531e-b8a4-4baf-bed2-d914242fa387",
|
||||
},
|
||||
{
|
||||
adapter: AdapterCopilot, fixture: "copilot/mcp.jsonl",
|
||||
wantCalls: []ToolCallReport{{Tool: "record_verdict", Detail: "record_verdict recorded"}},
|
||||
wantSession: "46ce5d05-adf6-45ac-82bc-167a3c48a146",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.fixture+tc.stopAt, func(t *testing.T) {
|
||||
adapter, ok := LookupHarnessAdapter(tc.adapter)
|
||||
if !ok {
|
||||
t.Fatalf("adapter %q is not registered", tc.adapter)
|
||||
}
|
||||
stream, err := os.Open("testdata/" + tc.fixture)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer stream.Close()
|
||||
|
||||
output := adapter.NewOutput()
|
||||
var calls []ToolCallReport
|
||||
report := func(call ToolCallReport) { calls = append(calls, call) }
|
||||
output.Line([]byte("{not json"), report)
|
||||
scanner := bufio.NewScanner(stream)
|
||||
scanner.Buffer(nil, 1<<20)
|
||||
for scanner.Scan() {
|
||||
if tc.stopAt != "" && strings.Contains(scanner.Text(), tc.stopAt) {
|
||||
break
|
||||
}
|
||||
output.Line(scanner.Bytes(), report)
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(calls, tc.wantCalls) {
|
||||
t.Errorf("tool calls = %#v, want %#v", calls, tc.wantCalls)
|
||||
}
|
||||
if got := output.SessionID(); got != tc.wantSession {
|
||||
t.Errorf("session ID = %q, want %q", got, tc.wantSession)
|
||||
}
|
||||
if got := output.Usage(); got != tc.wantUsage {
|
||||
t.Errorf("usage = %#v, want %#v", got, tc.wantUsage)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,428 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// fakeHarness is a stand-in coding-agent CLI. FAKE_SCENARIO picks what it
|
||||
// does to the workspace; every invocation's arguments are appended to
|
||||
// FAKE_LOG, and it prints a session line and a tool line for the adapter.
|
||||
const fakeHarness = `#!/bin/sh
|
||||
printf '%s' "$*" | tr '\n' ' ' >> "$FAKE_LOG"
|
||||
echo >> "$FAKE_LOG"
|
||||
case "$FAKE_SCENARIO" in
|
||||
edit) echo hello > notes.txt ;;
|
||||
commit) echo x > a.txt; git add a.txt; git -c user.email=a@b.c -c user.name=a commit -qm sneaky ;;
|
||||
config) git config remote.origin.url https://attacker.invalid/repo.git ;;
|
||||
protected) echo broken >> widget_test.go ;;
|
||||
sleep) sleep 30 & echo $! > "$FAKE_LOG.child"; wait ;;
|
||||
env) env > "$FAKE_LOG.env" ;;
|
||||
capture)
|
||||
cfg=""; prev=""
|
||||
for a in "$@"; do [ "$prev" = "--mcp-config" ] && cfg="$a"; prev="$a"; done
|
||||
out=$(sed -n 's/.*"-captures","\([^"]*\)".*/\1/p' "$cfg")
|
||||
echo '{"tool":"record_finding","args":{"title":"found it"}}' >> "$out"
|
||||
echo '{"tool":"record_finding","args":{"severity":"forged, no title"}}' >> "$out" ;;
|
||||
claude) echo '{"type":"system","subtype":"init","session_id":"C42"}' ;;
|
||||
fix-on-resume) if [ -f .attempted ]; then echo ok > fixed.txt; else touch .attempted; fi ;;
|
||||
esac
|
||||
echo "session=S123"
|
||||
echo "tool=edit_file"
|
||||
`
|
||||
|
||||
// lineOutput is a test adapter over fakeHarness's output lines.
|
||||
type lineOutput struct {
|
||||
mu sync.Mutex
|
||||
session string
|
||||
}
|
||||
|
||||
func (o *lineOutput) Line(line []byte, report ToolCallReporter) {
|
||||
text := string(line)
|
||||
switch {
|
||||
case strings.HasPrefix(text, "session="):
|
||||
o.mu.Lock()
|
||||
o.session = strings.TrimPrefix(text, "session=")
|
||||
o.mu.Unlock()
|
||||
case strings.HasPrefix(text, "tool=") && report != nil:
|
||||
report(ToolCallReport{Tool: strings.TrimPrefix(text, "tool=")})
|
||||
}
|
||||
}
|
||||
|
||||
func (o *lineOutput) SessionID() string {
|
||||
o.mu.Lock()
|
||||
defer o.mu.Unlock()
|
||||
return o.session
|
||||
}
|
||||
|
||||
func (o *lineOutput) Usage() Usage { return Usage{} }
|
||||
|
||||
func runGit(t *testing.T, dir string, args ...string) {
|
||||
t.Helper()
|
||||
cmd := exec.CommandContext(t.Context(), "git", append([]string{"-c", "user.email=a@b.c", "-c", "user.name=a"}, args...)...)
|
||||
cmd.Dir = dir
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("git %v: %v\n%s", args, err, out)
|
||||
}
|
||||
}
|
||||
|
||||
// hostileSigningConfig writes a global git config that makes every commit
|
||||
// fail unless the fixture disables signing in the repository's own config.
|
||||
func hostileSigningConfig(t *testing.T) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "hostile.gitconfig")
|
||||
const cfg = "[user]\n\tname = Hostile\n\temail = hostile@example.com\n\tsigningkey = /nonexistent/signing-key\n[gpg]\n\tformat = ssh\n[commit]\n\tgpgsign = true\n"
|
||||
if err := os.WriteFile(path, []byte(cfg), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// TestFixtureSeedsARepositoryThatIgnoresHostSigningConfig pins the fixture's
|
||||
// hermeticity: it must not depend on the developer's global git identity or a
|
||||
// signing agent.
|
||||
func TestFixtureSeedsARepositoryThatIgnoresHostSigningConfig(t *testing.T) {
|
||||
t.Setenv("GIT_CONFIG_GLOBAL", hostileSigningConfig(t))
|
||||
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
|
||||
newFixture(t, "edit")
|
||||
}
|
||||
|
||||
type fixture struct {
|
||||
workspace string
|
||||
log string
|
||||
req Request
|
||||
}
|
||||
|
||||
func newFixture(t *testing.T, scenario string) *fixture {
|
||||
t.Helper()
|
||||
ws := t.TempDir()
|
||||
runGit(t, ws, "init", "-q")
|
||||
runGit(t, ws, "config", "commit.gpgsign", "false")
|
||||
if err := os.WriteFile(filepath.Join(ws, "widget_test.go"), []byte("package widget\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runGit(t, ws, "add", ".")
|
||||
runGit(t, ws, "commit", "-qm", "base")
|
||||
runGit(t, ws, "remote", "add", "origin", "https://forge.invalid/repo.git")
|
||||
|
||||
bin := filepath.Join(t.TempDir(), "fake-harness")
|
||||
if err := os.WriteFile(bin, []byte(fakeHarness), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
log := filepath.Join(t.TempDir(), "invocations")
|
||||
return &fixture{workspace: ws, log: log, req: Request{
|
||||
Version: ProtocolVersion, TaskID: 1, Attempt: 1, Stage: "implement", Model: "harness",
|
||||
Mission: "Write the notes file.",
|
||||
Budget: Budget{WallClock: 20 * time.Second},
|
||||
Harness: &HarnessSpec{
|
||||
Env: []string{"PATH=" + os.Getenv("PATH"), "FAKE_SCENARIO=" + scenario, "FAKE_LOG=" + log},
|
||||
Launch: []string{"/bin/sh", bin},
|
||||
Prompt: []string{"-p", "{{.Prompt}}"},
|
||||
Resume: []string{"--resume", "{{.SessionID}}"},
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
func (f *fixture) run(t *testing.T, ctx context.Context) (Result, []ToolCallReport) {
|
||||
t.Helper()
|
||||
var mu sync.Mutex
|
||||
var calls []ToolCallReport
|
||||
res, err := NewHarnessRunner(func() HarnessOutput { return &lineOutput{} }).Run(ctx, f.workspace, f.req, func(r ToolCallReport) {
|
||||
mu.Lock()
|
||||
calls = append(calls, r)
|
||||
mu.Unlock()
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
return res, calls
|
||||
}
|
||||
|
||||
func (f *fixture) invocations(t *testing.T) []string {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(f.log)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var out []string
|
||||
sc := bufio.NewScanner(bytes.NewReader(raw))
|
||||
for sc.Scan() {
|
||||
out = append(out, sc.Text())
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestHarnessRunsTheMissionAndReportsChanges(t *testing.T) {
|
||||
f := newFixture(t, "edit")
|
||||
res, calls := f.run(t, t.Context())
|
||||
if res.Status != StatusPassed {
|
||||
t.Fatalf("status %q (%s), want passed", res.Status, res.StopReason)
|
||||
}
|
||||
if !slices.Equal(res.Changes, []string{"notes.txt"}) {
|
||||
t.Fatalf("changes %v, want [notes.txt]", res.Changes)
|
||||
}
|
||||
if len(calls) != 1 || calls[0].Tool != "edit_file" {
|
||||
t.Fatalf("tool calls %v, want one edit_file", calls)
|
||||
}
|
||||
inv := f.invocations(t)
|
||||
if len(inv) != 1 || !strings.HasPrefix(inv[0], "-p ") || !strings.Contains(inv[0], "Write the notes file.") {
|
||||
t.Fatalf("invocations %q, want one headless prompt carrying the mission", inv)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHarnessGuaranteesHoldWhateverTheHarnessDoes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
scenario string
|
||||
setup func(*Request)
|
||||
want string
|
||||
}{
|
||||
{"a commit fails the step", "commit", nil, "git"},
|
||||
{"rewriting the git config fails the step", "config", nil, "git"},
|
||||
{"editing a protected path fails the step", "protected", func(r *Request) { r.Protection = Protection{Suffixes: []string{"_test.go"}} }, "widget_test.go"},
|
||||
{"writing in a read-only stage fails the step", "edit", func(r *Request) { r.ReadOnly = true }, "notes.txt"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
f := newFixture(t, tt.scenario)
|
||||
if tt.setup != nil {
|
||||
tt.setup(&f.req)
|
||||
}
|
||||
res, _ := f.run(t, t.Context())
|
||||
if res.Status != StatusParked || !strings.Contains(res.StopReason, StopPolicy) || !strings.Contains(res.Detail, tt.want) {
|
||||
t.Fatalf("status %q stop %q detail %q; want parked on policy naming %q", res.Status, res.StopReason, res.Detail, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHarnessIgnoresChangesThatPredateTheRun(t *testing.T) {
|
||||
f := newFixture(t, "edit")
|
||||
if err := os.WriteFile(filepath.Join(f.workspace, "earlier.txt"), []byte("from a previous stage\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.req.ReadOnly = false
|
||||
res, _ := f.run(t, t.Context())
|
||||
if !slices.Equal(res.Changes, []string{"notes.txt"}) {
|
||||
t.Fatalf("changes %v, want only what this run changed", res.Changes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHarnessBudgetAndCancellation(t *testing.T) {
|
||||
t.Run("the wall clock kills the harness", func(t *testing.T) {
|
||||
f := newFixture(t, "sleep")
|
||||
f.req.Budget.WallClock = 500 * time.Millisecond
|
||||
start := time.Now()
|
||||
res, _ := f.run(t, t.Context())
|
||||
if time.Since(start) > 10*time.Second {
|
||||
t.Fatalf("run took %s; the harness outlived its budget", time.Since(start))
|
||||
}
|
||||
if res.Status != StatusParked || res.StopReason != StopTimedOut {
|
||||
t.Fatalf("status %q stop %q, want parked timed_out", res.Status, res.StopReason)
|
||||
}
|
||||
assertChildDead(t, f.log+".child")
|
||||
})
|
||||
t.Run("cancelling the run kills the harness", func(t *testing.T) {
|
||||
f := newFixture(t, "sleep")
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
time.AfterFunc(300*time.Millisecond, cancel)
|
||||
start := time.Now()
|
||||
_, err := NewHarnessRunner(func() HarnessOutput { return &lineOutput{} }).Run(ctx, f.workspace, f.req, nil)
|
||||
if time.Since(start) > 10*time.Second {
|
||||
t.Fatalf("cancel took %s", time.Since(start))
|
||||
}
|
||||
if err == nil || ctx.Err() == nil {
|
||||
t.Fatalf("Run after cancel returned %v, want the cancellation", err)
|
||||
}
|
||||
assertChildDead(t, f.log+".child")
|
||||
})
|
||||
}
|
||||
|
||||
func TestHarnessGateResumesTheSession(t *testing.T) {
|
||||
gate := Gate{Commands: []Command{{Name: "fixed", Argv: []string{"test", "-f", "fixed.txt"}}}, MaxConsecutiveFailures: 3}
|
||||
|
||||
t.Run("a failed gate resumes the same session with its output", func(t *testing.T) {
|
||||
f := newFixture(t, "fix-on-resume")
|
||||
f.req.Gate = gate
|
||||
res, _ := f.run(t, t.Context())
|
||||
if res.Status != StatusPassed || res.Iterations != 2 {
|
||||
t.Fatalf("status %q after %d iterations (%s), want passed after 2", res.Status, res.Iterations, res.StopReason)
|
||||
}
|
||||
inv := f.invocations(t)
|
||||
if len(inv) != 2 || !strings.HasPrefix(inv[1], "--resume S123 -p ") || !strings.Contains(inv[1], "[fixed]") {
|
||||
t.Fatalf("invocations %q, want a resume of S123 carrying the gate failure", inv)
|
||||
}
|
||||
})
|
||||
t.Run("a gate that never passes parks after the cap", func(t *testing.T) {
|
||||
f := newFixture(t, "edit")
|
||||
f.req.Gate = gate
|
||||
res, _ := f.run(t, t.Context())
|
||||
if res.Status != StatusParked || res.Iterations != 3 {
|
||||
t.Fatalf("status %q after %d iterations, want parked after 3", res.Status, res.Iterations)
|
||||
}
|
||||
})
|
||||
t.Run("a gate retry without a resume verb is refused before any invocation", func(t *testing.T) {
|
||||
f := newFixture(t, "fix-on-resume")
|
||||
f.req.Gate = gate
|
||||
f.req.Harness.Resume = nil
|
||||
if _, err := NewHarnessRunner(nil).Run(t.Context(), f.workspace, f.req, nil); err == nil || len(f.invocations(t)) != 0 {
|
||||
t.Fatalf("err %v after %d invocations, want a refusal before the harness ran", err, len(f.invocations(t)))
|
||||
}
|
||||
})
|
||||
t.Run("a single-attempt gate needs no resume verb", func(t *testing.T) {
|
||||
f := newFixture(t, "edit")
|
||||
f.req.Gate = Gate{Commands: gate.Commands, MaxConsecutiveFailures: 1}
|
||||
f.req.Harness.Resume = nil
|
||||
res, _ := f.run(t, t.Context())
|
||||
if res.Status != StatusParked || res.Iterations != 1 {
|
||||
t.Fatalf("status %q after %d iterations, want parked after 1", res.Status, res.Iterations)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestHarnessRequestValidation(t *testing.T) {
|
||||
f := newFixture(t, "edit")
|
||||
f.req.Harness.Prompt = []string{"-p"}
|
||||
if _, err := NewHarnessRunner(nil).Run(t.Context(), f.workspace, f.req, nil); err == nil {
|
||||
t.Fatal("a prompt verb with no {{.Prompt}} placeholder ran; the mission would be silently dropped")
|
||||
}
|
||||
f.req.Harness.Prompt = []string{"-p", "{{.Prompt}}"}
|
||||
f.req.Harness.Adapter = "no-such-cli"
|
||||
if _, err := NewHarnessRunner(nil).Run(t.Context(), f.workspace, f.req, nil); err == nil {
|
||||
t.Fatal("an unknown output adapter ran; its output would be read by nothing")
|
||||
}
|
||||
f.req.Harness = nil
|
||||
if _, err := NewHarnessRunner(nil).Run(t.Context(), f.workspace, f.req, nil); err == nil {
|
||||
t.Fatal("a request without a harness spec ran on the harness runner")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHarnessReadsOutputWithTheNamedAdapter(t *testing.T) {
|
||||
f := newFixture(t, "claude")
|
||||
f.req.Harness.Adapter = AdapterClaudeCode
|
||||
f.req.Gate = Gate{Commands: []Command{{Name: "never", Argv: []string{"false"}}}, MaxConsecutiveFailures: 2}
|
||||
if _, err := NewHarnessRunner(nil).Run(t.Context(), f.workspace, f.req, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inv := f.invocations(t)
|
||||
if len(inv) != 2 || !strings.HasPrefix(inv[1], "--resume C42 ") {
|
||||
t.Fatalf("invocations %q, want a resume of the session the Claude Code adapter read", inv)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaudeCodeAdapterRegistersTheMCPServer(t *testing.T) {
|
||||
a, ok := LookupHarnessAdapter(AdapterClaudeCode)
|
||||
if !ok || !slices.ContainsFunc(a.MCPConfig, func(s string) bool { return strings.Contains(s, mcpConfigPlaceholder) }) {
|
||||
t.Fatalf("adapter %+v: capture tools could never reach a Claude Code stage", a)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHarnessStagesRunEveryStageOnTheTasksHarness(t *testing.T) {
|
||||
inner := &namedRunner{}
|
||||
r := HarnessStages{Runner: inner, Spec: HarnessSpec{Adapter: AdapterClaudeCode}}
|
||||
if _, err := r.Run(t.Context(), "", Request{Stage: "review"}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if inner.got.Harness == nil || inner.got.Harness.Adapter != AdapterClaudeCode {
|
||||
t.Fatalf("stage ran with harness %+v, want the task's", inner.got.Harness)
|
||||
}
|
||||
}
|
||||
|
||||
type namedRunner struct{ got Request }
|
||||
|
||||
func (r *namedRunner) Run(_ context.Context, _ string, req Request, _ ToolCallReporter) (Result, error) {
|
||||
r.got = req
|
||||
return Result{}, nil
|
||||
}
|
||||
|
||||
// assertChildDead checks the harness's own child process did not outlive
|
||||
// it: killing only the CLI would leave its subprocesses running.
|
||||
func assertChildDead(t *testing.T, pidFile string) {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(pidFile)
|
||||
if err != nil {
|
||||
t.Fatalf("the harness recorded no child: %v", err)
|
||||
}
|
||||
pid, err := strconv.Atoi(strings.TrimSpace(string(raw)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for syscall.Kill(pid, 0) == nil {
|
||||
if time.Now().After(deadline) {
|
||||
_ = syscall.Kill(pid, syscall.SIGKILL)
|
||||
t.Fatalf("harness child %d outlived the step", pid)
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHarnessNeverInheritsTheWorkerEnvironment(t *testing.T) {
|
||||
f := newFixture(t, "env")
|
||||
// The fake's own variables are in the worker's environment too, so an
|
||||
// inherited environment would run the fake fully and expose the leak.
|
||||
t.Setenv("FAKE_SCENARIO", "env")
|
||||
t.Setenv("FAKE_LOG", f.log)
|
||||
t.Setenv("STATE_STORE_TOKEN", "worker-secret")
|
||||
t.Setenv("NATS_TOKEN", "worker-secret")
|
||||
f.req.Harness.Env = []string{
|
||||
"PATH=" + os.Getenv("PATH"),
|
||||
"FAKE_SCENARIO=env", "FAKE_LOG=" + f.log,
|
||||
"HTTPS_PROXY=http://archie:token@archie-egress:3128",
|
||||
}
|
||||
res, _ := f.run(t, t.Context())
|
||||
if res.Status != StatusPassed {
|
||||
t.Fatalf("status %q (%s)", res.Status, res.Detail)
|
||||
}
|
||||
raw, err := os.ReadFile(f.log + ".env")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
env := string(raw)
|
||||
if strings.Contains(env, "worker-secret") {
|
||||
t.Fatalf("the harness saw the worker's credentials:\n%s", env)
|
||||
}
|
||||
if !strings.Contains(env, "HTTPS_PROXY=http://archie:token@archie-egress:3128") {
|
||||
t.Fatalf("the harness did not get its declared environment:\n%s", env)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHarnessUser(t *testing.T) {
|
||||
tests := []struct {
|
||||
user string
|
||||
uid uint32
|
||||
gid uint32
|
||||
wantErr bool
|
||||
}{
|
||||
{"1000", 1000, 1000, false},
|
||||
{"1000:1001", 1000, 1001, false},
|
||||
{"0", 0, 0, true},
|
||||
{"root", 0, 0, true},
|
||||
{"not-a-user-anywhere", 0, 0, true},
|
||||
{"2147483648", 0, 0, true},
|
||||
{"1000:2147483648", 0, 0, true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
cred, err := harnessCredential(tt.user)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Errorf("harnessCredential(%q) = %+v, want an error", tt.user, cred)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err != nil || cred.Uid != tt.uid || cred.Gid != tt.gid {
|
||||
t.Errorf("harnessCredential(%q) = %+v, %v; want %d:%d", tt.user, cred, err, tt.uid, tt.gid)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,392 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/agentloop"
|
||||
"github.com/samcharles93/ai-sdk/chat"
|
||||
"github.com/samcharles93/ai-sdk/runtime"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
func TestPluginToolSetExecutesBundledPlugin(t *testing.T) {
|
||||
set, err := pluginToolSet(Request{Plugins: []PluginSpec{{Name: "echo", Src: "package main\nfunc Run(input string) string { return input + \"!\" }"}}}, t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tool := set["echo"]
|
||||
got, err := tool.Execute(context.Background(), `{"input":"hello"}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != "hello!" {
|
||||
t.Errorf("plugin output = %q, want hello!", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPluginToolSetExcludedFromConstrainedStages(t *testing.T) {
|
||||
requests := []Request{
|
||||
{ReadOnly: true, Plugins: []PluginSpec{{Name: "unsafe"}}},
|
||||
{Protection: Protection{Suffixes: []string{"_test.go"}}, Plugins: []PluginSpec{{Name: "unsafe"}}},
|
||||
{Gate: Gate{Commands: []Command{{Name: "test"}}}, Plugins: []PluginSpec{{Name: "unsafe"}}},
|
||||
}
|
||||
for _, request := range requests {
|
||||
set, err := pluginToolSet(request, t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(set) != 0 {
|
||||
t.Error("plugin tool exposed in constrained stage")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPluginToolSetRejectsAgentLoopCollisions(t *testing.T) {
|
||||
for _, name := range []string{"write", "finish"} {
|
||||
_, err := pluginToolSet(Request{Plugins: []PluginSpec{{Name: name}}}, t.TempDir())
|
||||
if err == nil {
|
||||
t.Errorf("plugin %q did not conflict with agent-loop tool", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoopRunnerMapsRequestAndCapturesOutput(t *testing.T) {
|
||||
runner := &LoopRunner{
|
||||
runtime: runtime.NewRuntime(runtime.Config{}),
|
||||
run: func(ctx context.Context, cfg agentloop.Config) (agentloop.Result, error) {
|
||||
if cfg.WorkDir != "/workspace" || cfg.ModelRef != "provider/model" || cfg.Mission != "mission" {
|
||||
t.Fatalf("unexpected config: workdir=%q model=%q mission=%q", cfg.WorkDir, cfg.ModelRef, cfg.Mission)
|
||||
}
|
||||
if cfg.ProtectPaths == nil || !cfg.ProtectPaths("nested/file_test.go") || !cfg.ProtectPaths("view_templ.go") {
|
||||
t.Fatal("declarative path protection was not applied")
|
||||
}
|
||||
if cfg.Completion != agentloop.CompletionForceFinish {
|
||||
t.Fatalf("Completion = %q, want forced finish recovery", cfg.Completion)
|
||||
}
|
||||
if !cfg.Compact.Enabled || cfg.Compact.ContextWindow <= 0 {
|
||||
t.Fatalf("Compact = %#v, want adaptive non-blocking history compaction", cfg.Compact)
|
||||
}
|
||||
if !strings.Contains(cfg.ExtraRules, "Confine discovery to /workspace") ||
|
||||
!strings.Contains(cfg.ExtraRules, "unless the mission explicitly requests") {
|
||||
t.Fatalf("project discovery rule missing from ExtraRules: %q", cfg.ExtraRules)
|
||||
}
|
||||
if err := cfg.Notes.Append(ctx, "verified note"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := cfg.Extra["decide"].Execute(ctx, `{"fit":true}`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return agentloop.Result{
|
||||
Status: agentloop.StatusPassed, Summary: "done", TokensUsed: 10,
|
||||
Usage: chat.Usage{PromptTokens: 8, CompletionTokens: 2, TotalTokens: 10, CachedTokens: 6},
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
req := Request{
|
||||
Version: ProtocolVersion, TaskID: 1, Attempt: 1, Stage: "assess", Model: "provider/model", ContextWindow: 120_000, Mission: "mission",
|
||||
Protection: Protection{Suffixes: []string{"_templ.go"}, Globs: []string{"*_test.go"}},
|
||||
CaptureTools: []CaptureTool{{Name: "decide", Parameters: json.RawMessage(`{"type":"object"}`), MaxCalls: 1}},
|
||||
}
|
||||
got, err := runner.Run(context.Background(), "/workspace", req, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Status != StatusPassed || got.Summary != "done" || got.TokensUsed != 10 {
|
||||
t.Fatalf("unexpected result: %#v", got)
|
||||
}
|
||||
if got.Usage.PromptTokens != 8 || got.Usage.CompletionTokens != 2 || got.Usage.CachedTokens != 6 {
|
||||
t.Fatalf("usage = %#v, want provider breakdown", got.Usage)
|
||||
}
|
||||
if len(got.AppendedNotes) != 1 || got.AppendedNotes[0] != "verified note" {
|
||||
t.Fatalf("appended notes = %v", got.AppendedNotes)
|
||||
}
|
||||
if len(got.Captures["decide"]) != 1 || string(got.Captures["decide"][0]) != `{"fit":true}` {
|
||||
t.Fatalf("captures = %v", got.Captures)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoopRunnerIncludesAvailableCentralTools(t *testing.T) {
|
||||
registry := tools.NewRegistry()
|
||||
if err := registry.Register(tools.ToolEntry{
|
||||
Name: "memory_search",
|
||||
Handler: func(context.Context, map[string]any) (any, error) {
|
||||
return "found", nil
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner := &LoopRunner{
|
||||
runtime: runtime.NewRuntime(runtime.Config{}),
|
||||
tools: registry,
|
||||
run: func(ctx context.Context, cfg agentloop.Config) (agentloop.Result, error) {
|
||||
tool, ok := cfg.Extra["memory_search"]
|
||||
if !ok {
|
||||
t.Fatal("central tool is not present in agentloop Config.Extra")
|
||||
}
|
||||
got, err := tool.Execute(ctx, `{}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != `"found"` {
|
||||
t.Fatalf("tool output = %q, want JSON string", got)
|
||||
}
|
||||
return agentloop.Result{Status: agentloop.StatusPassed}, nil
|
||||
},
|
||||
}
|
||||
_, err := runner.Run(context.Background(), "/workspace", Request{
|
||||
Version: ProtocolVersion,
|
||||
TaskID: 1,
|
||||
Attempt: 1,
|
||||
Stage: "build",
|
||||
Model: "provider/model",
|
||||
Mission: "mission",
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoopRunnerRejectsInvalidCentralToolSchemas(t *testing.T) {
|
||||
registry := tools.NewRegistry()
|
||||
if err := registry.Register(tools.ToolEntry{
|
||||
Name: "invalid",
|
||||
Handler: func(context.Context, map[string]any) (any, error) { return nil, nil },
|
||||
DynamicSchemaOverrides: func(tools.JSONSchema) tools.JSONSchema {
|
||||
panic("schema panic")
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner := &LoopRunner{
|
||||
runtime: runtime.NewRuntime(runtime.Config{}),
|
||||
tools: registry,
|
||||
run: func(context.Context, agentloop.Config) (agentloop.Result, error) {
|
||||
t.Fatal("agent loop ran with an invalid central tool schema")
|
||||
return agentloop.Result{}, nil
|
||||
},
|
||||
}
|
||||
_, err := runner.Run(context.Background(), "/workspace", Request{
|
||||
Version: ProtocolVersion,
|
||||
TaskID: 1,
|
||||
Attempt: 1,
|
||||
Stage: "build",
|
||||
Model: "provider/model",
|
||||
Mission: "mission",
|
||||
}, nil)
|
||||
if err == nil {
|
||||
t.Fatal("Run() error = nil, want invalid central tool schema error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtectionMatcherAppliesBasenameAndPathGlobs(t *testing.T) {
|
||||
match := protectionMatcher(Protection{Globs: []string{"*_test.go", "tests/*.rs"}}, false)
|
||||
tests := []struct {
|
||||
path string
|
||||
want bool
|
||||
}{
|
||||
{path: "main_test.go", want: true},
|
||||
{path: "internal/foo/bar_test.go", want: true},
|
||||
{path: "tests/widget.rs", want: true},
|
||||
{path: "src/widget.rs", want: false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := match(tt.path); got != tt.want {
|
||||
t.Errorf("match(%q) = %v, want %v", tt.path, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureToolRejectsInvalidDataBeforeRecording(t *testing.T) {
|
||||
captures := make(map[string][]json.RawMessage)
|
||||
tool := captureToolSet([]CaptureTool{{
|
||||
Name: "decide", RequiredFields: []string{"fit", "reasons"}, NonEmptyStrings: []string{"reasons"},
|
||||
BooleanFields: []string{"fit"},
|
||||
}}, captures)["decide"]
|
||||
output, err := tool.Execute(context.Background(), `{"fit":true,"reasons":""}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(captures["decide"]) != 0 || output != "decide rejected: reasons must be a non-empty string" {
|
||||
t.Fatalf("invalid capture output=%q captures=%v", output, captures)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureToolRejectsWrongFieldTypeBeforeRecording(t *testing.T) {
|
||||
captures := make(map[string][]json.RawMessage)
|
||||
tool := captureToolSet([]CaptureTool{{Name: "decide", BooleanFields: []string{"fit"}}}, captures)["decide"]
|
||||
output, err := tool.Execute(context.Background(), `{"fit":"true"}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(captures["decide"]) != 0 || output != "decide rejected: fit must be a boolean" {
|
||||
t.Fatalf("invalid capture output=%q captures=%v", output, captures)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScriptToolRunsAGoScriptAndReturnsItsOutput(t *testing.T) {
|
||||
workspace := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(workspace, "scripts"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
src := "package main\n\nimport \"fmt\"\n\nfunc main() { fmt.Println(\"hi from a script\") }\n"
|
||||
if err := os.WriteFile(filepath.Join(workspace, "scripts", "hello.go"), []byte(src), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tool := scriptToolSet(workspace)["run_go_script"]
|
||||
out, err := tool.Execute(context.Background(), `{"path":"scripts/hello.go"}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out != "hi from a script\n" {
|
||||
t.Fatalf("run_go_script output = %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScriptToolRejectsPathsEscapingTheWorkspace(t *testing.T) {
|
||||
workspace := t.TempDir()
|
||||
tool := scriptToolSet(workspace)["run_go_script"]
|
||||
out, err := tool.Execute(context.Background(), `{"path":"../outside.go"}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out != "run_go_script rejected: path escapes the workspace" {
|
||||
t.Fatalf("run_go_script output = %q, want a workspace-escape rejection", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScriptToolRejectsMissingPath(t *testing.T) {
|
||||
tool := scriptToolSet(t.TempDir())["run_go_script"]
|
||||
out, err := tool.Execute(context.Background(), `{}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out != "run_go_script rejected: arguments must be a JSON object with a non-empty path field" {
|
||||
t.Fatalf("run_go_script output = %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeToolSetsLaterWinsOnCollision(t *testing.T) {
|
||||
first := scriptToolSet(t.TempDir())
|
||||
captures := make(map[string][]json.RawMessage)
|
||||
second := captureToolSet([]CaptureTool{{Name: "run_go_script"}}, captures)
|
||||
merged := mergeToolSets(first, second)
|
||||
if len(merged) != 1 {
|
||||
t.Fatalf("merged = %v, want exactly one tool", merged)
|
||||
}
|
||||
if _, err := merged["run_go_script"].Execute(context.Background(), `{}`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(captures["run_go_script"]) != 1 {
|
||||
t.Fatalf("expected the capture tool (second set) to win, captures = %v", captures)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoopRunnerPreservesCallerCancellation(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
runner := &LoopRunner{
|
||||
runtime: runtime.NewRuntime(runtime.Config{}),
|
||||
run: func(context.Context, agentloop.Config) (agentloop.Result, error) {
|
||||
return agentloop.Result{Status: agentloop.StatusParked, StopReason: agentloop.StopTimedOut}, nil
|
||||
},
|
||||
}
|
||||
_, err := runner.Run(ctx, "/workspace", Request{
|
||||
Version: ProtocolVersion, TaskID: 1, Attempt: 1, Stage: "build", Model: "provider/model", Mission: "mission",
|
||||
}, nil)
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Run error = %v, want context.Canceled", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestScriptToolHonorsContextCancellation proves that the run_go_script
|
||||
// tool handler discards the incoming context (the handler is declared as
|
||||
// func(_ context.Context, input string) and calls skillscript.Run without
|
||||
// forwarding ctx). Every other execution path in archie-core respects
|
||||
// context cancellation (LoopRunner checks context.Cause), but a
|
||||
// cancelled/timed-out context
|
||||
// has zero effect on run_go_script — a blocking script wedges the
|
||||
// goroutine permanently.
|
||||
func TestScriptToolHonorsContextCancellation(t *testing.T) {
|
||||
workspace := t.TempDir()
|
||||
src := `package main
|
||||
|
||||
func main() {
|
||||
select {}
|
||||
}
|
||||
`
|
||||
if err := os.WriteFile(filepath.Join(workspace, "blocker.go"), []byte(src), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel() // immediately cancelled — the tool should return promptly
|
||||
|
||||
tool := scriptToolSet(workspace)["run_go_script"]
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
// The result is irrelevant here -- this goroutine only exists to
|
||||
// prove Execute returns promptly once ctx is cancelled.
|
||||
_, _ = tool.Execute(ctx, `{"path":"blocker.go"}`)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
// After the fix, the tool returns quickly because the cancelled
|
||||
// context propagates through to skillscript.Run, which selects
|
||||
// on ctx.Done() and abandons the blocking EvalPath goroutine.
|
||||
t.Log("run_go_script returned promptly (context was honored)")
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Error("run_go_script ignores context cancellation: " +
|
||||
"the handler discards its context parameter (declared as _) " +
|
||||
"and calls skillscript.Run without forwarding it (issue #45)")
|
||||
}
|
||||
}
|
||||
|
||||
// A profile's allowlist removes the tools archie adds that it does not name,
|
||||
// but never a stage's capture tools, which carry its structured result.
|
||||
func TestLoopRunnerAppliesTheProfileAllowlist(t *testing.T) {
|
||||
registry := tools.NewRegistry()
|
||||
for _, name := range []string{"whois", "memory_search"} {
|
||||
if err := registry.Register(tools.ToolEntry{
|
||||
Name: name,
|
||||
Handler: func(context.Context, map[string]any) (any, error) { return "", nil },
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var extra []string
|
||||
runner := &LoopRunner{
|
||||
runtime: runtime.NewRuntime(runtime.Config{}),
|
||||
tools: registry,
|
||||
AllowTools: []string{"whois"},
|
||||
run: func(_ context.Context, cfg agentloop.Config) (agentloop.Result, error) {
|
||||
for name := range cfg.Extra {
|
||||
extra = append(extra, name)
|
||||
}
|
||||
return agentloop.Result{Status: agentloop.StatusPassed}, nil
|
||||
},
|
||||
}
|
||||
_, err := runner.Run(context.Background(), t.TempDir(), Request{
|
||||
Version: ProtocolVersion, TaskID: 1, Attempt: 1, Stage: "build", Model: "provider/model", Mission: "mission",
|
||||
CaptureTools: []CaptureTool{{Name: "report", Description: "d", Parameters: json.RawMessage(`{"type":"object"}`)}},
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
slices.Sort(extra)
|
||||
if !slices.Equal(extra, []string{"report", "whois"}) {
|
||||
t.Fatalf("agent tools = %v, want the allowed whois and the capture tool", extra)
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestProtocolRoundTrip(t *testing.T) {
|
||||
want := Request{
|
||||
Version: ProtocolVersion, TaskID: 42, Attempt: 3, Stage: "fix", Model: "openai/gpt-5",
|
||||
Mission: "fix it", Budget: Budget{MaxSteps: 12, WallClock: 2 * time.Minute},
|
||||
Gate: Gate{Commands: []Command{{Name: "go", Argv: []string{"go", "test", "./..."}}}, MaxConsecutiveFailures: 2},
|
||||
Protection: Protection{Suffixes: []string{"_templ.go"}, Globs: []string{"*_test.go"}},
|
||||
CaptureTools: []CaptureTool{{Name: "decide", Parameters: json.RawMessage(`{"type":"object"}`), MaxCalls: 1}},
|
||||
}
|
||||
b, err := json.Marshal(want)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got Request
|
||||
if err := json.Unmarshal(b, &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("round trip mismatch\ngot: %#v\nwant: %#v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestRejectsUnknownProtocol(t *testing.T) {
|
||||
req := Request{Version: ProtocolVersion + 1, TaskID: 1, Stage: "plan", Model: "provider/model"}
|
||||
if err := req.Validate(); err == nil {
|
||||
t.Fatal("Validate accepted an unsupported protocol version")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResultRejectsMismatchedIdentity(t *testing.T) {
|
||||
req := Request{Version: ProtocolVersion, TaskID: 1, Attempt: 2, Stage: "build", Model: "provider/model"}
|
||||
result := Result{
|
||||
Version: ProtocolVersion, TaskID: 1, Attempt: 3, Stage: "build", Status: StatusPassed,
|
||||
}
|
||||
if err := result.ValidateFor(req); err == nil {
|
||||
t.Fatal("ValidateFor accepted a result from another attempt")
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
func TestProvidersFromConfig(t *testing.T) {
|
||||
in := map[string]config.Provider{
|
||||
"anthropic": {Class: "anthropic", APIKeyEnv: "ANTHROPIC_API_KEY", BaseURL: "https://api.anthropic.com"},
|
||||
}
|
||||
want := map[string]Provider{
|
||||
"anthropic": {Class: "anthropic", APIKeyEnv: "ANTHROPIC_API_KEY", BaseURL: "https://api.anthropic.com"},
|
||||
}
|
||||
if got := ProvidersFromConfig(in); !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("ProvidersFromConfig() = %#v, want %#v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvidersFromConfigEmpty(t *testing.T) {
|
||||
if got := ProvidersFromConfig(nil); len(got) != 0 {
|
||||
t.Fatalf("ProvidersFromConfig(nil) = %#v, want empty", got)
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/chat"
|
||||
|
||||
protocol "github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
)
|
||||
|
||||
func TestSamplingMessagesMapsRolesAndRejectsUnsupportedInput(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
request protocol.SamplingRequest
|
||||
want []chat.Message
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "user and assistant text map to chat roles",
|
||||
request: protocol.SamplingRequest{Messages: []protocol.SamplingMessage{
|
||||
{Role: "user", Content: protocol.SamplingContent{Type: "text", Text: "2+2?"}},
|
||||
{Role: "assistant", Content: protocol.SamplingContent{Type: "", Text: "4"}},
|
||||
}},
|
||||
want: []chat.Message{
|
||||
{Role: chat.RoleUser, Content: "2+2?"},
|
||||
{Role: chat.RoleAssistant, Content: "4"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "no messages is a refusal",
|
||||
request: protocol.SamplingRequest{},
|
||||
wantErr: "the request has no messages",
|
||||
},
|
||||
{
|
||||
name: "non-text content is a refusal",
|
||||
request: protocol.SamplingRequest{Messages: []protocol.SamplingMessage{
|
||||
{Role: "user", Content: protocol.SamplingContent{Type: "image"}},
|
||||
}},
|
||||
wantErr: "unsupported content type",
|
||||
},
|
||||
{
|
||||
name: "unknown role is a refusal",
|
||||
request: protocol.SamplingRequest{Messages: []protocol.SamplingMessage{
|
||||
{Role: "system", Content: protocol.SamplingContent{Type: "text", Text: "hi"}},
|
||||
}},
|
||||
wantErr: "unsupported role",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, err := SamplingMessages(tc.request)
|
||||
if tc.wantErr != "" {
|
||||
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
|
||||
t.Fatalf("SamplingMessages error = %v, want it to mention %q", err, tc.wantErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("SamplingMessages error = %v, want nil", err)
|
||||
}
|
||||
if len(got) != len(tc.want) {
|
||||
t.Fatalf("SamplingMessages returned %d messages, want %d", len(got), len(tc.want))
|
||||
}
|
||||
for i := range got {
|
||||
if got[i].Role != tc.want[i].Role || got[i].Content != tc.want[i].Content {
|
||||
t.Errorf("message %d = %+v, want %+v", i, got[i], tc.want[i])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSamplingMaxTokens(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
requested int
|
||||
ceiling int
|
||||
reasoning bool
|
||||
wantTokens int
|
||||
}{
|
||||
{name: "requested bound is honoured", requested: 64, ceiling: 1024, wantTokens: 64},
|
||||
{name: "absent request falls back to the default", requested: 0, ceiling: 8192, wantTokens: DefaultSamplingMaxTokens},
|
||||
{name: "request is capped by the model ceiling", requested: 8192, ceiling: 1024, wantTokens: 1024},
|
||||
{name: "unknown ceiling keeps the request", requested: 8192, ceiling: 0, wantTokens: 8192},
|
||||
{name: "reasoning model gets no bound", requested: 64, ceiling: 1024, reasoning: true, wantTokens: 0},
|
||||
{name: "reasoning model with absent request gets no bound", requested: 0, ceiling: 0, reasoning: true, wantTokens: 0},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := SamplingMaxTokens(tc.requested, tc.ceiling, tc.reasoning); got != tc.wantTokens {
|
||||
t.Fatalf("SamplingMaxTokens(%d, %d, %v) = %d, want %d", tc.requested, tc.ceiling, tc.reasoning, got, tc.wantTokens)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestTaskIDFromSystemSubject pins the round trip with SubjectForSystem, and
|
||||
// that a subject which merely resembles one (wrong kind suffix, malformed
|
||||
// ID) is rejected rather than parsed into a wrong task ID -- a daemon
|
||||
// demuxing a wildcard subscription onto SubjectSystemWildcard has no other
|
||||
// check on what actually arrives.
|
||||
func TestTaskIDFromSystemSubject(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
subject string
|
||||
wantID int64
|
||||
wantOK bool
|
||||
}{
|
||||
{"round trip with SubjectForSystem", SubjectForSystem(42), 42, true},
|
||||
{"round trip with a large ID", SubjectForSystem(9_223_372_036), 9_223_372_036, true},
|
||||
{"wrong kind suffix is rejected", "archie.agent.42.response", 0, false},
|
||||
{"missing prefix is rejected", "some.other.42.system", 0, false},
|
||||
{"non-numeric ID is rejected", "archie.agent.abc.system", 0, false},
|
||||
{"zero ID is rejected", "archie.agent.0.system", 0, false},
|
||||
{"negative ID is rejected", "archie.agent.-1.system", 0, false},
|
||||
{"empty subject is rejected", "", 0, false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
gotID, gotOK := TaskIDFromSystemSubject(tt.subject)
|
||||
if gotID != tt.wantID || gotOK != tt.wantOK {
|
||||
t.Errorf("TaskIDFromSystemSubject(%q) = (%d, %v), want (%d, %v)",
|
||||
tt.subject, gotID, gotOK, tt.wantID, tt.wantOK)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubjectSystemWildcardMatchesEverySystemSubject(t *testing.T) {
|
||||
tests := []int64{1, 42, 9_223_372_036}
|
||||
for _, taskID := range tests {
|
||||
if id, ok := TaskIDFromSystemSubject(SubjectForSystem(taskID)); !ok || id != taskID {
|
||||
t.Errorf("SubjectForSystem(%d) did not round-trip through TaskIDFromSystemSubject: got (%d, %v)", taskID, id, ok)
|
||||
}
|
||||
}
|
||||
if SubjectSystemWildcard != "archie.agent.*.system" {
|
||||
t.Errorf("SubjectSystemWildcard = %q, want the single-token wildcard NATS matches against subjectForTask's shape",
|
||||
SubjectSystemWildcard)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskIDFromEventsSubject mirrors TestTaskIDFromSystemSubject: a daemon
|
||||
// demuxing SubjectEventsWildcard has no other check on what arrives, so a
|
||||
// subject that merely resembles one must be rejected, not parsed into a
|
||||
// wrong task ID.
|
||||
func TestTaskIDFromEventsSubject(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
subject string
|
||||
wantID int64
|
||||
wantOK bool
|
||||
}{
|
||||
{"round trip with SubjectForEvents", SubjectForEvents(42), 42, true},
|
||||
{"round trip with a large ID", SubjectForEvents(9_223_372_036), 9_223_372_036, true},
|
||||
{"wrong kind suffix is rejected", "archie.agent.42.system", 0, false},
|
||||
{"missing prefix is rejected", "some.other.42.events", 0, false},
|
||||
{"non-numeric ID is rejected", "archie.agent.abc.events", 0, false},
|
||||
{"zero ID is rejected", "archie.agent.0.events", 0, false},
|
||||
{"negative ID is rejected", "archie.agent.-1.events", 0, false},
|
||||
{"empty subject is rejected", "", 0, false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
gotID, gotOK := TaskIDFromEventsSubject(tt.subject)
|
||||
if gotID != tt.wantID || gotOK != tt.wantOK {
|
||||
t.Errorf("TaskIDFromEventsSubject(%q) = (%d, %v), want (%d, %v)",
|
||||
tt.subject, gotID, gotOK, tt.wantID, tt.wantOK)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubjectEventsWildcardMatchesEveryEventsSubject(t *testing.T) {
|
||||
tests := []int64{1, 42, 9_223_372_036}
|
||||
for _, taskID := range tests {
|
||||
if id, ok := TaskIDFromEventsSubject(SubjectForEvents(taskID)); !ok || id != taskID {
|
||||
t.Errorf("SubjectForEvents(%d) did not round-trip through TaskIDFromEventsSubject: got (%d, %v)", taskID, id, ok)
|
||||
}
|
||||
}
|
||||
if SubjectEventsWildcard != "archie.agent.*.events" {
|
||||
t.Errorf("SubjectEventsWildcard = %q, want the single-token wildcard NATS matches against subjectForTask's shape",
|
||||
SubjectEventsWildcard)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEventsAndSystemSubjectsDoNotCrossMatch guards the reason a dedicated
|
||||
// events subject exists instead of reusing SubjectForSystem: the daemon
|
||||
// already owns one payload format per subject (logging.Entry on .system),
|
||||
// and a task event decoded as a log entry (or vice versa) would silently
|
||||
// corrupt whichever table receives it.
|
||||
func TestEventsAndSystemSubjectsDoNotCrossMatch(t *testing.T) {
|
||||
if _, ok := TaskIDFromSystemSubject(SubjectForEvents(7)); ok {
|
||||
t.Error("TaskIDFromSystemSubject accepted an events subject")
|
||||
}
|
||||
if _, ok := TaskIDFromEventsSubject(SubjectForSystem(7)); ok {
|
||||
t.Error("TaskIDFromEventsSubject accepted a system subject")
|
||||
}
|
||||
}
|
||||
@@ -1,238 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
|
||||
// fakePublisher is a LogPublisher that records every call and can be told to
|
||||
// fail, so tests can assert both the happy path and the "must never block or
|
||||
// fail the run" requirement.
|
||||
type fakePublisher struct {
|
||||
mu sync.Mutex
|
||||
subjects []string
|
||||
payloads [][]byte
|
||||
failWith error
|
||||
}
|
||||
|
||||
func (f *fakePublisher) Publish(subject string, data []byte) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.subjects = append(f.subjects, subject)
|
||||
f.payloads = append(f.payloads, append([]byte(nil), data...))
|
||||
return f.failWith
|
||||
}
|
||||
|
||||
func (f *fakePublisher) calls() int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return len(f.payloads)
|
||||
}
|
||||
|
||||
// capturingHandler is a minimal slog.Handler that records every record it
|
||||
// receives, standing in for the agentworker's wrapped process stderr handler.
|
||||
type capturingHandler struct {
|
||||
mu sync.Mutex
|
||||
records []slog.Record
|
||||
}
|
||||
|
||||
func (h *capturingHandler) Enabled(context.Context, slog.Level) bool { return true }
|
||||
|
||||
func (h *capturingHandler) Handle(_ context.Context, r slog.Record) error {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.records = append(h.records, r)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *capturingHandler) WithAttrs([]slog.Attr) slog.Handler { return h }
|
||||
func (h *capturingHandler) WithGroup(string) slog.Handler { return h }
|
||||
|
||||
func (h *capturingHandler) messages() []string {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
out := make([]string, len(h.records))
|
||||
for i, r := range h.records {
|
||||
out[i] = r.Message
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestSystemLogHandlerPublishesToTheTasksSystemSubject(t *testing.T) {
|
||||
pub := &fakePublisher{}
|
||||
next := &capturingHandler{}
|
||||
handler := NewSystemLogHandler(next, pub, 42)
|
||||
logger := slog.New(handler)
|
||||
|
||||
logger.Warn("gate failed", "component", "gate")
|
||||
|
||||
if got, want := pub.calls(), 1; got != want {
|
||||
t.Fatalf("publish calls = %d, want %d", got, want)
|
||||
}
|
||||
if got, want := pub.subjects[0], SubjectForSystem(42); got != want {
|
||||
t.Errorf("subject = %q, want %q", got, want)
|
||||
}
|
||||
|
||||
var entry logging.Entry
|
||||
if err := json.Unmarshal(pub.payloads[0], &entry); err != nil {
|
||||
t.Fatalf("payload is not a logging.Entry: %v", err)
|
||||
}
|
||||
if entry.Message != "gate failed" {
|
||||
t.Errorf("Message = %q, want %q", entry.Message, "gate failed")
|
||||
}
|
||||
if entry.Level != "WARN" {
|
||||
t.Errorf("Level = %q, want WARN", entry.Level)
|
||||
}
|
||||
if entry.Fields["component"] != "gate" {
|
||||
t.Errorf("Fields[component] = %v, want gate", entry.Fields["component"])
|
||||
}
|
||||
// The wire entry must carry the record's own event time. The daemon files
|
||||
// a task's records under the time the event happened (see
|
||||
// logging.TaskRegistry.Write), so a producer that dropped or re-stamped it
|
||||
// here would collapse a run's timing before it ever left the container.
|
||||
next.mu.Lock()
|
||||
wantTime := next.records[0].Time
|
||||
next.mu.Unlock()
|
||||
if entry.Time.IsZero() {
|
||||
t.Error("Entry.Time is the zero time, want the record's own event time")
|
||||
} else if !entry.Time.Equal(wantTime) {
|
||||
t.Errorf("Entry.Time = %s, want the record's event time %s", entry.Time, wantTime)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSystemLogHandlerAlwaysTeesToNextRegardlessOfPublishOutcome(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
failWith error
|
||||
}{
|
||||
{name: "publish succeeds"},
|
||||
{name: "publish fails", failWith: errors.New("nats: no responders")},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
pub := &fakePublisher{failWith: tt.failWith}
|
||||
next := &capturingHandler{}
|
||||
logger := slog.New(NewSystemLogHandler(next, pub, 1))
|
||||
|
||||
logger.Info("still visible on stderr")
|
||||
|
||||
// A failed publish also emits its own one-time warning onto
|
||||
// next (see TestSystemLogHandlerLogsPublishFailureOnceNotPerRecord),
|
||||
// so check membership, not position.
|
||||
found := false
|
||||
for _, msg := range next.messages() {
|
||||
found = found || msg == "still visible on stderr"
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("next handler messages = %v, want %q present regardless of publish outcome",
|
||||
next.messages(), "still visible on stderr")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSystemLogHandlerNeverFailsTheRunOnPublishError guards the explicit
|
||||
// design requirement: log shipping must never block or fail the run it is
|
||||
// reporting on. A slog.Logger call that returned an error here would
|
||||
// propagate nowhere useful (slog callers never check it), but Handle itself
|
||||
// must not return a publish error either, or a handler chain that does check
|
||||
// (as ours might grow to) would start treating a dead NATS connection as a
|
||||
// logging failure worth surfacing to the caller.
|
||||
func TestSystemLogHandlerNeverFailsTheRunOnPublishError(t *testing.T) {
|
||||
pub := &fakePublisher{failWith: errors.New("nats: no responders")}
|
||||
handler := NewSystemLogHandler(&capturingHandler{}, pub, 1)
|
||||
|
||||
rec := slog.NewRecord(time.Now(), slog.LevelInfo, "msg", 0)
|
||||
if err := handler.Handle(context.Background(), rec); err != nil {
|
||||
t.Errorf("Handle() = %v, want nil even when the publisher errors", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSystemLogHandlerLogsPublishFailureOnceNotPerRecord guards against a
|
||||
// dead NATS connection turning every subsequent log line into a second
|
||||
// failure notice on stderr, which would drown out the very output the
|
||||
// operator is trying to read.
|
||||
func TestSystemLogHandlerLogsPublishFailureOnceNotPerRecord(t *testing.T) {
|
||||
pub := &fakePublisher{failWith: errors.New("nats: no responders")}
|
||||
next := &capturingHandler{}
|
||||
logger := slog.New(NewSystemLogHandler(next, pub, 1))
|
||||
|
||||
for range 5 {
|
||||
logger.Info("line")
|
||||
}
|
||||
|
||||
failureNotices := 0
|
||||
for _, msg := range next.messages() {
|
||||
if msg != "line" {
|
||||
failureNotices++
|
||||
}
|
||||
}
|
||||
if failureNotices != 1 {
|
||||
t.Errorf("failure notices on next = %d, want exactly 1 across 5 failed publishes", failureNotices)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSystemLogHandlerMarshalFailureWarnsOnceAndNeverPublishes guards the
|
||||
// other delivery failure mode alongside a rejected Publish: an attr value
|
||||
// json.Marshal can't encode (e.g. a channel) must not silently vanish with
|
||||
// zero signal, and must not reach the publisher with malformed data either.
|
||||
func TestSystemLogHandlerMarshalFailureWarnsOnceAndNeverPublishes(t *testing.T) {
|
||||
pub := &fakePublisher{}
|
||||
next := &capturingHandler{}
|
||||
logger := slog.New(NewSystemLogHandler(next, pub, 1))
|
||||
|
||||
logger.Info("unmarshalable", "bad", make(chan int))
|
||||
|
||||
if pub.calls() != 0 {
|
||||
t.Errorf("publish calls = %d, want 0: malformed data must never reach the publisher", pub.calls())
|
||||
}
|
||||
|
||||
failureNotices := 0
|
||||
for _, msg := range next.messages() {
|
||||
if msg != "unmarshalable" {
|
||||
failureNotices++
|
||||
}
|
||||
}
|
||||
if failureNotices != 1 {
|
||||
t.Errorf("failure notices on next = %d, want exactly 1", failureNotices)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSystemLogHandlerWithAttrsAndGroupsReachThePublishedEntry(t *testing.T) {
|
||||
pub := &fakePublisher{}
|
||||
next := &capturingHandler{}
|
||||
handler := NewSystemLogHandler(next, pub, 7)
|
||||
|
||||
logger := slog.New(handler).With("task", "7").WithGroup("gate")
|
||||
logger.Warn("failed", "cmd", "go build ./...")
|
||||
|
||||
if pub.calls() != 1 {
|
||||
t.Fatalf("publish calls = %d, want 1", pub.calls())
|
||||
}
|
||||
var entry logging.Entry
|
||||
if err := json.Unmarshal(pub.payloads[0], &entry); err != nil {
|
||||
t.Fatalf("payload is not a logging.Entry: %v", err)
|
||||
}
|
||||
if entry.Fields["task"] != "7" {
|
||||
t.Errorf("Fields[task] = %v, want 7 (WithAttrs before WithGroup keeps its own key ungrouped)", entry.Fields["task"])
|
||||
}
|
||||
if entry.Fields["gate.cmd"] != "go build ./..." {
|
||||
t.Errorf("Fields[gate.cmd] = %v, want %q", entry.Fields["gate.cmd"], "go build ./...")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSystemLogHandlerEnabledDelegatesToNext(t *testing.T) {
|
||||
next := &capturingHandler{}
|
||||
handler := NewSystemLogHandler(next, &fakePublisher{}, 1)
|
||||
if !handler.Enabled(context.Background(), slog.LevelInfo) {
|
||||
t.Error("Enabled() = false, want true (next always returns true)")
|
||||
}
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
var errPublishBoom = errors.New("publish boom")
|
||||
|
||||
// eventPublisherStub is an EventPublisher that records every call and can be
|
||||
// told to fail, mirroring fakePublisher in systemlog_test.go for the same
|
||||
// reason: assert both the happy path and "one failure must not stop the
|
||||
// rest."
|
||||
type eventPublisherStub struct {
|
||||
subjects []string
|
||||
payloads [][]byte
|
||||
failWith error
|
||||
}
|
||||
|
||||
func (p *eventPublisherStub) Publish(subject string, data []byte) error {
|
||||
p.subjects = append(p.subjects, subject)
|
||||
p.payloads = append(p.payloads, append([]byte(nil), data...))
|
||||
return p.failWith
|
||||
}
|
||||
|
||||
// TestForwardTaskEventsPublishesEachEventOnItsTaskSubject is the core
|
||||
// contract: everything published on the bus while ForwardTaskEvents is
|
||||
// running arrives at pub, JSON-decodable back into the same Event, on
|
||||
// SubjectForEvents(taskID) -- regardless of which task's events happen to be
|
||||
// flowing, since taskID is a ForwardTaskEvents parameter, not read from the
|
||||
// event itself.
|
||||
func TestForwardTaskEventsPublishesEachEventOnItsTaskSubject(t *testing.T) {
|
||||
bus := events.NewBus()
|
||||
sub := bus.Subscribe(8)
|
||||
pub := &eventPublisherStub{}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
ForwardTaskEvents(sub, pub, 42, slog.New(slog.DiscardHandler))
|
||||
close(done)
|
||||
}()
|
||||
|
||||
want := []events.Event{
|
||||
{Kind: events.KindStageStart, TaskID: 42, Stage: "baseline", Attempt: 1},
|
||||
{Kind: events.KindStageFinish, TaskID: 42, Stage: "baseline", Attempt: 1, Data: map[string]any{"duration_ms": float64(120)}},
|
||||
{Kind: events.KindParked, TaskID: 42, Attempt: 1, Detail: "baseline red"},
|
||||
// R4's document rides this bridge too: a worker captures its own
|
||||
// effective configuration, and the daemon is a different process, so
|
||||
// the payload has to survive the hop or the Config tab reads nothing.
|
||||
// The daemon's own key for it is asserted below by name.
|
||||
{Kind: events.KindConfigCaptured, TaskID: 42, Attempt: 1, Data: map[string]any{
|
||||
"schema": events.ConfigCapturedSchema,
|
||||
"document": map[string]any{"bot_user": "archie"},
|
||||
}},
|
||||
}
|
||||
for _, e := range want {
|
||||
bus.Publish(e)
|
||||
}
|
||||
sub.Close()
|
||||
<-done
|
||||
|
||||
if len(pub.payloads) != len(want) {
|
||||
t.Fatalf("published %d events, want %d", len(pub.payloads), len(want))
|
||||
}
|
||||
wantSubject := SubjectForEvents(42)
|
||||
for i, payload := range pub.payloads {
|
||||
if pub.subjects[i] != wantSubject {
|
||||
t.Errorf("event %d subject = %q, want %q", i, pub.subjects[i], wantSubject)
|
||||
}
|
||||
var got events.Event
|
||||
if err := json.Unmarshal(payload, &got); err != nil {
|
||||
t.Fatalf("event %d undecodable: %v", i, err)
|
||||
}
|
||||
if got.Kind != want[i].Kind || got.TaskID != want[i].TaskID || got.Stage != want[i].Stage || got.Detail != want[i].Detail {
|
||||
t.Errorf("event %d = %+v, want %+v", i, got, want[i])
|
||||
}
|
||||
if got.Attempt != want[i].Attempt {
|
||||
t.Errorf("event %d attempt = %d, want %d (provenance must not be dropped on the hop)", i, got.Attempt, want[i].Attempt)
|
||||
}
|
||||
if got.Kind == events.KindConfigCaptured {
|
||||
if got.Data["schema"] != events.ConfigCapturedSchema {
|
||||
t.Errorf("event %d schema = %v, want %q", i, got.Data["schema"], events.ConfigCapturedSchema)
|
||||
}
|
||||
if _, renamed := got.Data["config"]; renamed {
|
||||
t.Errorf(`event %d crossed under "config"; the producer writes the document under "document"`, i)
|
||||
}
|
||||
doc, ok := got.Data["document"].(map[string]any)
|
||||
if !ok || doc["bot_user"] != "archie" {
|
||||
t.Errorf("event %d document payload = %#v, want the decoded document under its own key", i, got.Data["document"])
|
||||
}
|
||||
}
|
||||
if got.At.IsZero() {
|
||||
t.Errorf("event %d has zero At, want the bus-stamped publish time", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestForwardTaskEventsSurvivesAPublishFailure pins "one missing event must
|
||||
// never abort the ones after it": event shipping must never block or fail
|
||||
// the workflow run it is reporting on.
|
||||
func TestForwardTaskEventsSurvivesAPublishFailure(t *testing.T) {
|
||||
bus := events.NewBus()
|
||||
sub := bus.Subscribe(8)
|
||||
pub := &eventPublisherStub{failWith: errPublishBoom}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
ForwardTaskEvents(sub, pub, 7, slog.New(slog.DiscardHandler))
|
||||
close(done)
|
||||
}()
|
||||
|
||||
bus.Publish(events.Event{Kind: events.KindStageStart, TaskID: 7})
|
||||
bus.Publish(events.Event{Kind: events.KindOutcome, TaskID: 7})
|
||||
sub.Close()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("ForwardTaskEvents did not return after sub.Close(); a publish failure blocked the loop")
|
||||
}
|
||||
|
||||
if len(pub.payloads) != 2 {
|
||||
t.Fatalf("published %d events despite failures, want 2 (both attempted)", len(pub.payloads))
|
||||
}
|
||||
}
|
||||
@@ -1,692 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
aicore "github.com/samcharles93/ai-sdk/core"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
func TestToolSetConvertsRegisteredEntries(t *testing.T) {
|
||||
reg := tools.NewRegistry()
|
||||
if err := reg.Register(tools.ToolEntry{
|
||||
Name: "echo",
|
||||
Description: "echoes its input",
|
||||
Schema: tools.JSONSchema{"type": "object", "properties": map[string]any{"msg": map[string]any{"type": "string"}}},
|
||||
Handler: func(_ context.Context, input map[string]any) (any, error) {
|
||||
return input["msg"], nil
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
set := mustBuildToolSet(t, reg)
|
||||
|
||||
tool, ok := set["echo"]
|
||||
if !ok {
|
||||
t.Fatal("ToolSet did not include the \"echo\" entry")
|
||||
}
|
||||
if tool.Name != "echo" || tool.Description != "echoes its input" {
|
||||
t.Errorf("tool = %+v", tool)
|
||||
}
|
||||
if len(tool.Parameters) == 0 {
|
||||
t.Error("Parameters is empty, want the marshaled schema")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolSetHandlerRoundTripsJSON(t *testing.T) {
|
||||
reg := tools.NewRegistry()
|
||||
if err := reg.Register(tools.ToolEntry{
|
||||
Name: "add",
|
||||
Handler: func(_ context.Context, input map[string]any) (any, error) {
|
||||
a, _ := input["a"].(float64)
|
||||
b, _ := input["b"].(float64)
|
||||
return a + b, nil
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
set := mustBuildToolSet(t, reg)
|
||||
out, err := set["add"].Execute(context.Background(), `{"a": 2, "b": 3}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got float64
|
||||
if err := json.Unmarshal([]byte(out), &got); err != nil {
|
||||
t.Fatalf("output %q did not decode as JSON: %v", out, err)
|
||||
}
|
||||
if got != 5 {
|
||||
t.Errorf("result = %v, want 5", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolSetHandlerPropagatesHandlerError(t *testing.T) {
|
||||
reg := tools.NewRegistry()
|
||||
wantErr := errors.New("boom")
|
||||
if err := reg.Register(tools.ToolEntry{
|
||||
Name: "fails",
|
||||
Handler: func(context.Context, map[string]any) (any, error) {
|
||||
return nil, wantErr
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
set := mustBuildToolSet(t, reg)
|
||||
_, err := set["fails"].Execute(context.Background(), `{}`)
|
||||
if err == nil {
|
||||
t.Fatal("expected error from failing handler")
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolSetReportsCompletedToolCalls pins archie-core-467's task-transcript
|
||||
// counterpart: every tool invocation built through BuildToolSet must notify
|
||||
// ToolSetOptions.OnToolCall exactly once, on both the success and failure
|
||||
// path, so a workflow stage can surface it on the task timeline.
|
||||
func TestToolSetReportsCompletedToolCalls(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
handler tools.Handler
|
||||
wantFailed bool
|
||||
wantDetail string
|
||||
}{
|
||||
{
|
||||
name: "success",
|
||||
handler: func(context.Context, map[string]any) (any, error) { return "wrote 3 lines", nil },
|
||||
wantFailed: false,
|
||||
wantDetail: `"wrote 3 lines"`,
|
||||
},
|
||||
{
|
||||
name: "failure",
|
||||
handler: func(context.Context, map[string]any) (any, error) { return nil, errors.New("permission denied") },
|
||||
wantFailed: true,
|
||||
wantDetail: "error: permission denied",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
reg := tools.NewRegistry()
|
||||
if err := reg.Register(tools.ToolEntry{Name: "write_file", Handler: tt.handler}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var reports []ToolCallReport
|
||||
set := mustBuildToolSetWith(t, reg, ToolSetOptions{
|
||||
OnToolCall: func(rep ToolCallReport) { reports = append(reports, rep) },
|
||||
})
|
||||
_, _ = set["write_file"].Execute(context.Background(), `{}`)
|
||||
|
||||
if len(reports) != 1 {
|
||||
t.Fatalf("OnToolCall was called %d times, want 1: %+v", len(reports), reports)
|
||||
}
|
||||
got := reports[0]
|
||||
if got.Tool != "write_file" {
|
||||
t.Errorf("Tool = %q, want %q", got.Tool, "write_file")
|
||||
}
|
||||
if got.Failed != tt.wantFailed {
|
||||
t.Errorf("Failed = %v, want %v", got.Failed, tt.wantFailed)
|
||||
}
|
||||
if got.Detail != tt.wantDetail {
|
||||
t.Errorf("Detail = %q, want %q", got.Detail, tt.wantDetail)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolSetHandlerRejectsMalformedInput(t *testing.T) {
|
||||
reg := tools.NewRegistry()
|
||||
if err := reg.Register(tools.ToolEntry{
|
||||
Name: "noop",
|
||||
Handler: func(context.Context, map[string]any) (any, error) { return "ok", nil },
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
set := mustBuildToolSet(t, reg)
|
||||
_, err := set["noop"].Execute(context.Background(), `not json`)
|
||||
if err == nil {
|
||||
t.Fatal("expected error decoding malformed input JSON")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolSetOmitsUnavailableTools(t *testing.T) {
|
||||
reg := tools.NewRegistry()
|
||||
if err := reg.Register(tools.ToolEntry{
|
||||
Name: "offline",
|
||||
Handler: func(context.Context, map[string]any) (any, error) { return nil, nil },
|
||||
CheckFn: func() bool { return false },
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
set := mustBuildToolSet(t, reg)
|
||||
if _, ok := set["offline"]; ok {
|
||||
t.Error("ToolSet included a tool whose CheckFn reports unavailable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolSetEmptyRegistryReturnsEmptySet(t *testing.T) {
|
||||
set := mustBuildToolSet(t, tools.NewRegistry())
|
||||
if len(set) != 0 {
|
||||
t.Errorf("len(set) = %d, want 0", len(set))
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolSetNilRegistryReturnsEmptySet(t *testing.T) {
|
||||
set := mustBuildToolSet(t, nil)
|
||||
if len(set) != 0 {
|
||||
t.Errorf("len(set) = %d, want 0 for nil registry", len(set))
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolSetUsesObjectSchemaForParameterlessTools(t *testing.T) {
|
||||
reg := tools.NewRegistry()
|
||||
if err := reg.Register(tools.ToolEntry{
|
||||
Name: "no_args",
|
||||
Handler: func(context.Context, map[string]any) (any, error) { return nil, nil },
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
parameters := mustBuildToolSet(t, reg)["no_args"].Parameters
|
||||
var schema map[string]any
|
||||
if err := json.Unmarshal(parameters, &schema); err != nil {
|
||||
t.Fatalf("Parameters = %s, want JSON object: %v", parameters, err)
|
||||
}
|
||||
if schema["type"] != "object" {
|
||||
t.Fatalf("Parameters = %s, want object schema", parameters)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolSetHandlerReturningNilOutputProducesNullJSON(t *testing.T) {
|
||||
reg := tools.NewRegistry()
|
||||
if err := reg.Register(tools.ToolEntry{
|
||||
Name: "voidy",
|
||||
Handler: func(context.Context, map[string]any) (any, error) { return nil, nil },
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
set := mustBuildToolSet(t, reg)
|
||||
out, err := set["voidy"].Execute(context.Background(), `{}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out != "null" {
|
||||
t.Errorf("output = %q, want \"null\"", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildToolSetReportsInvalidDynamicSchemas(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
entry tools.ToolEntry
|
||||
}{
|
||||
{
|
||||
name: "schema override panic",
|
||||
entry: tools.ToolEntry{
|
||||
Name: "panics",
|
||||
Handler: func(context.Context, map[string]any) (any, error) { return nil, nil },
|
||||
DynamicSchemaOverrides: func(tools.JSONSchema) tools.JSONSchema {
|
||||
panic("schema panic")
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unmarshalable schema",
|
||||
entry: tools.ToolEntry{
|
||||
Name: "invalid",
|
||||
Schema: tools.JSONSchema{"bad": func() {}},
|
||||
Handler: func(context.Context, map[string]any) (any, error) { return nil, nil },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "availability panic",
|
||||
entry: tools.ToolEntry{
|
||||
Name: "unavailable",
|
||||
Handler: func(context.Context, map[string]any) (any, error) { return nil, nil },
|
||||
CheckFn: func() bool {
|
||||
panic("availability panic")
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
registry := tools.NewRegistry()
|
||||
if err := registry.Register(tt.entry); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var (
|
||||
err error
|
||||
panicked any
|
||||
)
|
||||
func() {
|
||||
defer func() { panicked = recover() }()
|
||||
_, err = BuildToolSet(registry, ToolSetOptions{})
|
||||
}()
|
||||
if panicked != nil {
|
||||
t.Fatalf("BuildToolSet() panicked: %v", panicked)
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatal("BuildToolSet() error = nil, want invalid schema error")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func mustBuildToolSet(t *testing.T, registry *tools.Registry) map[string]*aicore.Tool {
|
||||
t.Helper()
|
||||
return mustBuildToolSetWith(t, registry, ToolSetOptions{})
|
||||
}
|
||||
|
||||
func mustBuildToolSetWith(t *testing.T, registry *tools.Registry, opts ToolSetOptions) map[string]*aicore.Tool {
|
||||
t.Helper()
|
||||
set, err := BuildToolSet(registry, opts)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
// registryReturning builds a single-entry registry whose tool returns payload.
|
||||
func registryReturning(t *testing.T, entry tools.ToolEntry, payload string) *tools.Registry {
|
||||
t.Helper()
|
||||
reg := tools.NewRegistry()
|
||||
entry.Handler = func(context.Context, map[string]any) (any, error) { return payload, nil }
|
||||
if err := reg.Register(entry); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return reg
|
||||
}
|
||||
|
||||
// TestToolSetCapsResults covers the limit that decides how much of a tool
|
||||
// result reaches the model. The workspace tools truncate themselves, so the
|
||||
// entries that matter here are the ones that do not: skill bodies and MCP
|
||||
// results were previously handed over whole.
|
||||
func TestToolSetCapsResults(t *testing.T) {
|
||||
const payloadSize = 4000
|
||||
payload := strings.Repeat("z", payloadSize)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
entryLimit int // ToolEntry.MaxResultSizeChars
|
||||
defaultLimit int // ToolSetOptions.MaxResultChars
|
||||
wantTruncated bool
|
||||
}{
|
||||
{name: "under the default passes through", defaultLimit: payloadSize * 2},
|
||||
{name: "over the default is capped", defaultLimit: 100, wantTruncated: true},
|
||||
{name: "per-entry limit overrides a larger default", entryLimit: 100, defaultLimit: payloadSize * 2, wantTruncated: true},
|
||||
{name: "per-entry limit overrides a smaller default", entryLimit: payloadSize * 2, defaultLimit: 100},
|
||||
{name: "negative default disables capping", defaultLimit: -1},
|
||||
{name: "zero default disables capping", defaultLimit: 0},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
reg := registryReturning(t, tools.ToolEntry{
|
||||
Name: "big",
|
||||
MaxResultSizeChars: tc.entryLimit,
|
||||
}, payload)
|
||||
|
||||
set := mustBuildToolSetWith(t, reg, ToolSetOptions{MaxResultChars: tc.defaultLimit})
|
||||
out, err := set["big"].Execute(context.Background(), "{}")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
truncated := strings.Contains(out, "truncated")
|
||||
if truncated != tc.wantTruncated {
|
||||
t.Fatalf("truncated = %v, want %v (result %d bytes)", truncated, tc.wantTruncated, len(out))
|
||||
}
|
||||
if !tc.wantTruncated && len(out) < payloadSize {
|
||||
t.Errorf("result is %d bytes, want the whole %d-byte payload", len(out), payloadSize)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolSetSpillsOversizeResults proves an oversized result is displaced to
|
||||
// disk rather than lost: the model gets a path it can read back with the read
|
||||
// tool, which is the whole point of spilling instead of truncating.
|
||||
func TestToolSetSpillsOversizeResults(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
payload := strings.Repeat("q", 4000)
|
||||
|
||||
reg := registryReturning(t, tools.ToolEntry{Name: "big"}, payload)
|
||||
set := mustBuildToolSetWith(t, reg, ToolSetOptions{MaxResultChars: 100, SpillDir: dir})
|
||||
|
||||
out, err := set["big"].Execute(context.Background(), "{}")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(out, "spilled") {
|
||||
t.Fatalf("result = %q, want a spill reference", out)
|
||||
}
|
||||
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil || len(entries) != 1 {
|
||||
t.Fatalf("spill directory entries = %v, err = %v; want one spill", entries, err)
|
||||
}
|
||||
spillPath := filepath.Join(dir, entries[0].Name())
|
||||
if !strings.Contains(out, spillPath) {
|
||||
t.Errorf("result %q does not name the spill path %q", out, spillPath)
|
||||
}
|
||||
body, err := os.ReadFile(spillPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(body), payload) {
|
||||
t.Error("spill file does not hold the full payload")
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolLimitsCreatesSpillDir covers the gap that made spilling dead code in
|
||||
// production: the configured directory was never created, so every oversized
|
||||
// result silently fell back to inline truncation.
|
||||
func TestToolLimitsCreatesSpillDir(t *testing.T) {
|
||||
// A nested path proves the whole tree is created, not just a leaf.
|
||||
dir := filepath.Join(t.TempDir(), "work", "tool-spill")
|
||||
limits := ToolLimits{MaxResultChars: 100, SpillDir: dir}
|
||||
|
||||
if err := limits.EnsureSpillDir(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
info, err := os.Stat(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("spill directory was not created: %v", err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
t.Fatalf("%s is not a directory", dir)
|
||||
}
|
||||
|
||||
// And a spill actually lands there once it exists.
|
||||
reg := registryReturning(t, tools.ToolEntry{Name: "big"}, strings.Repeat("z", 5000))
|
||||
set := mustBuildToolSetWith(t, reg, limits.Options())
|
||||
if _, err := set["big"].Execute(context.Background(), "{}"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
t.Error("no spill file was written into the created directory")
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolLimitsEnsureSpillDirNoop covers the disabled case: no directory
|
||||
// configured is not an error, it selects inline truncation.
|
||||
func TestToolLimitsEnsureSpillDirNoop(t *testing.T) {
|
||||
if err := (ToolLimits{}).EnsureSpillDir(); err != nil {
|
||||
t.Errorf("EnsureSpillDir() with no directory = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Tool result volume is bounded per invocation only. Repeated large results
|
||||
// may each be spilled or truncated, but accumulation never stops the turn.
|
||||
func TestToolSetPerResultLimitNeverStopsFurtherCalls(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
spillDir bool
|
||||
}{
|
||||
{name: "results spilled to disk", spillDir: true},
|
||||
{name: "results truncated inline", spillDir: false},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := ""
|
||||
if tc.spillDir {
|
||||
dir = t.TempDir()
|
||||
}
|
||||
reg := registryReturning(t, tools.ToolEntry{Name: "big"}, strings.Repeat("q", 60_000))
|
||||
set := mustBuildToolSetWith(t, reg, ToolSetOptions{MaxResultChars: 100, SpillDir: dir})
|
||||
|
||||
for range 5 {
|
||||
_, err := set["big"].Execute(context.Background(), "{}")
|
||||
if err != nil {
|
||||
t.Fatalf("later tool call was stopped by accumulated output: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolSetExcludesToolsets covers the task-agent case: a task runs in its
|
||||
// own worktree, so the chat workspace's file and shell tools must not follow it
|
||||
// in and bypass the agent loop's read-only and protected-path enforcement.
|
||||
func TestToolSetExcludesToolsets(t *testing.T) {
|
||||
reg := tools.NewRegistry()
|
||||
for _, e := range []tools.ToolEntry{
|
||||
{Name: "shell", Toolset: "workspace"},
|
||||
{Name: "memory_edit", Toolset: "memory"},
|
||||
} {
|
||||
e.Handler = func(context.Context, map[string]any) (any, error) { return "ok", nil }
|
||||
if err := reg.Register(e); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
full := mustBuildToolSetWith(t, reg, ToolSetOptions{})
|
||||
if len(full) != 2 {
|
||||
t.Fatalf("with no exclusions the set has %d tools, want 2", len(full))
|
||||
}
|
||||
|
||||
limited := mustBuildToolSetWith(t, reg, ToolSetOptions{ExcludeToolsets: []string{"workspace"}})
|
||||
if _, ok := limited["shell"]; ok {
|
||||
t.Error("workspace tool survived the exclusion")
|
||||
}
|
||||
if _, ok := limited["memory_edit"]; !ok {
|
||||
t.Error("memory tool was dropped, want only the workspace toolset excluded")
|
||||
}
|
||||
}
|
||||
|
||||
// testApprover is a scripted ApprovalRequester for the tool-approval gate
|
||||
// tests. It returns whatever decision and error the test wired up, so each
|
||||
// test exercises one branch of the gate.
|
||||
type testApprover struct {
|
||||
decision tools.ApprovalDecision
|
||||
err error
|
||||
}
|
||||
|
||||
func (a *testApprover) RequestApproval(context.Context, string, string) (tools.ApprovalDecision, error) {
|
||||
return a.decision, a.err
|
||||
}
|
||||
|
||||
// approvalEntry returns a single-entry registry whose tool is marked
|
||||
// RequiresApproval and records whether its handler ran.
|
||||
func approvalEntry(t *testing.T, reg *tools.Registry, ran *bool) {
|
||||
t.Helper()
|
||||
if err := reg.Register(tools.ToolEntry{
|
||||
Name: "gated",
|
||||
Description: "requires human consent",
|
||||
Classification: tools.RequiresApproval,
|
||||
Handler: func(context.Context, map[string]any) (any, error) {
|
||||
*ran = true
|
||||
return "ran", nil
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolSetApprovalApprovedExecutes(t *testing.T) {
|
||||
reg := tools.NewRegistry()
|
||||
ran := false
|
||||
approvalEntry(t, reg, &ran)
|
||||
|
||||
set := mustBuildToolSetWith(t, reg, ToolSetOptions{Approval: &testApprover{decision: tools.ApprovalApproved}})
|
||||
out, err := set["gated"].Execute(context.Background(), `{}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !ran {
|
||||
t.Error("handler did not run after approval was granted")
|
||||
}
|
||||
if out != `"ran"` {
|
||||
t.Errorf("output = %q, want \"ran\"", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolSetApprovalDeniedReturnsError(t *testing.T) {
|
||||
reg := tools.NewRegistry()
|
||||
ran := false
|
||||
approvalEntry(t, reg, &ran)
|
||||
|
||||
set := mustBuildToolSetWith(t, reg, ToolSetOptions{Approval: &testApprover{decision: tools.ApprovalDenied}})
|
||||
_, err := set["gated"].Execute(context.Background(), `{}`)
|
||||
if err == nil {
|
||||
t.Fatal("expected an error when approval is denied")
|
||||
}
|
||||
if !errors.Is(err, tools.ErrApprovalDenied) {
|
||||
t.Errorf("error = %v, want it to wrap ErrApprovalDenied", err)
|
||||
}
|
||||
if ran {
|
||||
t.Error("handler ran despite the denial")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolSetApprovalPropagatesApproverError(t *testing.T) {
|
||||
reg := tools.NewRegistry()
|
||||
ran := false
|
||||
approvalEntry(t, reg, &ran)
|
||||
|
||||
wantErr := errors.New("approver exploded")
|
||||
set := mustBuildToolSetWith(t, reg, ToolSetOptions{Approval: &testApprover{err: wantErr}})
|
||||
_, err := set["gated"].Execute(context.Background(), `{}`)
|
||||
if err == nil {
|
||||
t.Fatal("expected an error from the approver")
|
||||
}
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Errorf("error = %v, want it to wrap the approver error", err)
|
||||
}
|
||||
if ran {
|
||||
t.Error("handler ran despite the approver error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolSetApprovalMissingApproverReturnsError(t *testing.T) {
|
||||
ran := false
|
||||
entry := tools.ToolEntry{
|
||||
Name: "gated",
|
||||
Description: "requires human consent",
|
||||
Classification: tools.RequiresApproval,
|
||||
Handler: func(context.Context, map[string]any) (any, error) {
|
||||
ran = true
|
||||
return "should not run", nil
|
||||
},
|
||||
}
|
||||
// The build-time gate omits approval-requiring tools from a set built
|
||||
// without an approver, so exercise the runtime gate directly: the execute
|
||||
// closure must still refuse to run the tool.
|
||||
tool := aicore.NewTool(entry.Name, entry.Description, json.RawMessage(`{"type":"object","properties":{}}`), toolExecute(entry, ToolSetOptions{}))
|
||||
_, err := tool.Execute(context.Background(), `{}`)
|
||||
if err == nil {
|
||||
t.Fatal("expected an error when no approver is configured")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "no approver") {
|
||||
t.Errorf("error = %v, want it to name the missing approver", err)
|
||||
}
|
||||
if ran {
|
||||
t.Error("handler ran despite there being no approver")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolSetWithoutApprovalFlagExecutesNormally(t *testing.T) {
|
||||
reg := tools.NewRegistry()
|
||||
if err := reg.Register(tools.ToolEntry{
|
||||
Name: "plain",
|
||||
Handler: func(context.Context, map[string]any) (any, error) { return "ok", nil },
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Even with an approver that would deny, a non-gated tool must run.
|
||||
set := mustBuildToolSetWith(t, reg, ToolSetOptions{Approval: &testApprover{decision: tools.ApprovalDenied}})
|
||||
out, err := set["plain"].Execute(context.Background(), `{}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out != `"ok"` {
|
||||
t.Errorf("output = %q, want \"ok\"", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildToolSetOmitsApprovalToolsWithoutApprover(t *testing.T) {
|
||||
reg := tools.NewRegistry()
|
||||
if err := reg.Register(tools.ToolEntry{
|
||||
Name: "gated",
|
||||
Description: "requires human consent",
|
||||
Classification: tools.RequiresApproval,
|
||||
Handler: func(context.Context, map[string]any) (any, error) { return nil, nil },
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := reg.Register(tools.ToolEntry{
|
||||
Name: "plain",
|
||||
Handler: func(context.Context, map[string]any) (any, error) { return nil, nil },
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
set := mustBuildToolSetWith(t, reg, ToolSetOptions{})
|
||||
if _, ok := set["gated"]; ok {
|
||||
t.Error("ToolSet included an approval-requiring tool with no approver")
|
||||
}
|
||||
if _, ok := set["plain"]; !ok {
|
||||
t.Error("ToolSet dropped a non-approval tool")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildToolSetIncludesApprovalToolsWithApprover(t *testing.T) {
|
||||
reg := tools.NewRegistry()
|
||||
if err := reg.Register(tools.ToolEntry{
|
||||
Name: "gated",
|
||||
Description: "requires human consent",
|
||||
Classification: tools.RequiresApproval,
|
||||
Handler: func(context.Context, map[string]any) (any, error) { return nil, nil },
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
set := mustBuildToolSetWith(t, reg, ToolSetOptions{Approval: &testApprover{decision: tools.ApprovalApproved}})
|
||||
if _, ok := set["gated"]; !ok {
|
||||
t.Error("ToolSet omitted an approval-requiring tool with an approver configured")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolSetApprovalFailsClosedOnUnknownDecision(t *testing.T) {
|
||||
reg := tools.NewRegistry()
|
||||
ran := false
|
||||
approvalEntry(t, reg, &ran)
|
||||
|
||||
// ApprovalDecision 999 is not a recognised constant. The gate must
|
||||
// fail closed: an unknown value from a faulty approver must not
|
||||
// execute the tool.
|
||||
unknownDecision := tools.ApprovalDecision(999)
|
||||
set := mustBuildToolSetWith(t, reg, ToolSetOptions{Approval: &testApprover{decision: unknownDecision}})
|
||||
tool, ok := set["gated"]
|
||||
if !ok {
|
||||
t.Fatal("tool not in set")
|
||||
}
|
||||
_, err := tool.Execute(context.Background(), `{}`)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for unknown decision, got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "unexpected decision") {
|
||||
t.Errorf("error = %v, want 'unexpected decision'", err)
|
||||
}
|
||||
if ran {
|
||||
t.Error("tool executed despite unknown approval decision")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user