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")
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package agentworker
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestApplicationOwnsNoTransportWireMechanics(t *testing.T) {
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, path := range files {
|
||||
if strings.HasSuffix(path, "_test.go") {
|
||||
continue
|
||||
}
|
||||
file, err := parser.ParseFile(token.NewFileSet(), path, nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, imported := range file.Imports {
|
||||
name, err := strconv.Unquote(imported.Path.Value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
switch {
|
||||
case name == "encoding/json":
|
||||
t.Errorf("%s imports JSON wire encoding", path)
|
||||
case name == "github.com/samcharles93/archie-core/internal/domain/workintake":
|
||||
t.Errorf("%s imports NATS topology subjects", path)
|
||||
case name == "github.com/nats-io/nats.go" || strings.HasPrefix(name, "github.com/nats-io/nats.go/"):
|
||||
t.Errorf("%s imports raw NATS SDK package %q", path, name)
|
||||
}
|
||||
}
|
||||
ast.Inspect(file, func(node ast.Node) bool {
|
||||
selector, ok := node.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
if selector.Sel.Name == "ReplyAddress" || selector.Sel.Name == "Subject" || selector.Sel.Name == "Data" {
|
||||
t.Errorf("%s inspects transport wire selector %s", path, selector.Sel.Name)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Full-task request/reply is the worker's only production entry point. A
|
||||
// single-stage loop would recreate the obsolete split where archied owns the
|
||||
// workflow and remotely invokes each stage.
|
||||
func TestApplicationContainsNoSingleStageWorkerLoop(t *testing.T) {
|
||||
for _, path := range []string{"single_stage_request.go", "stage_loop.go"} {
|
||||
matches, err := filepath.Glob(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(matches) != 0 {
|
||||
t.Errorf("legacy single-stage worker file still exists: %s", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
package agentworker
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// guardrailRunYAML is a repository-none workflow with one agent stage: a task
|
||||
// run reaches AgentStage.handleResult once, and the engine that recorded that
|
||||
// outcome is observable by its call count and by the decision a low threshold
|
||||
// earns.
|
||||
const guardrailRunYAML = "id: guardrail\nrepository: none\nsteps:\n" +
|
||||
" - type: agent.run\n settings:\n mission: first\n"
|
||||
|
||||
// TestProductionWorkerDependenciesBuildGuardrails pins the producer: the
|
||||
// process that runs agent stages is archie-agent, so its composition root must
|
||||
// build the guardrail engine every TaskContext records against. A daemon-built
|
||||
// engine can never reach this process -- it is a separate binary -- so before
|
||||
// this wiring TaskContext.Guardrails was nil on every production run and no
|
||||
// decision was ever recorded.
|
||||
func TestProductionWorkerDependenciesBuildGuardrails(t *testing.T) {
|
||||
deps, err := productionWorkerDependencies()
|
||||
if err != nil {
|
||||
t.Fatalf("productionWorkerDependencies: %v", err)
|
||||
}
|
||||
if deps.guardrails == nil {
|
||||
t.Fatal("worker composition built no guardrail engine: TaskContext.Guardrails stays nil and no agent-stage decision is recorded")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTaskRecordsGuardrailDecision is the end-to-end half: a workflow run
|
||||
// whose TaskContext carries the engine records its agent stage's outcome. Before
|
||||
// the wiring the engine was never assigned, so the run recorded zero -- the
|
||||
// guardrail engine observed nothing for any task.
|
||||
func TestRunTaskRecordsGuardrailDecision(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
st := pgstore.Open(t)
|
||||
|
||||
task, err := st.EnqueueChatTask(ctx, "", "", "guardrail recording", "", "guardrail", "", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("seed task: %v", err)
|
||||
}
|
||||
if err := st.Transition(ctx, task.ID, task.Status, workflow.StatusRunning, "started"); err != nil {
|
||||
t.Fatalf("claim task: %v", err)
|
||||
}
|
||||
task.Status = workflow.StatusRunning
|
||||
task.WorkflowDefinitionYAML = guardrailRunYAML
|
||||
task.WorkflowDefinitionDigest = workflow.DigestDefinition(guardrailRunYAML)
|
||||
if err := st.Update(ctx, task); err != nil {
|
||||
t.Fatalf("seed task: %v", err)
|
||||
}
|
||||
|
||||
workDir := t.TempDir()
|
||||
// A threshold a single stage reaches turns the recorded outcome into an
|
||||
// actual guardrail decision, so the test proves the run consulted the
|
||||
// engine rather than merely holding a reference.
|
||||
engine := tools.NewGuardrailEngine(tools.ToolCallGuardrailConfig{
|
||||
NoProgressWarnAfter: 1,
|
||||
HardStopAfterWarnRepeat: 1,
|
||||
})
|
||||
request := taskrun.Request{
|
||||
Task: task,
|
||||
Repo: config.Repo{},
|
||||
Cfg: config.Config{Models: map[string]string{"builder": "p/m"}}.ForTask(),
|
||||
WorkflowDefinition: guardrailRunYAML,
|
||||
}
|
||||
dependencies := taskDependencies{
|
||||
store: st,
|
||||
trees: &fakeScratchTrees{dir: workDir},
|
||||
steps: testSteps(t),
|
||||
guardrails: engine,
|
||||
}
|
||||
fakeRunner := runnerFactory(func(map[string]agentexec.Provider, *slog.Logger) agentexec.Runner {
|
||||
return stubRunner{}
|
||||
})
|
||||
if _, err := runTask(ctx, request, dependencies, fakeRunner, workDir, slog.New(slog.DiscardHandler)); err != nil {
|
||||
t.Fatalf("runTask: %v", err)
|
||||
}
|
||||
|
||||
if got := engine.TotalCalls(); got != 1 {
|
||||
t.Fatalf("guardrail engine recorded %d tool outcomes, want 1 (the agent stage): TaskContext.Guardrails is not wired to the engine the run was given", got)
|
||||
}
|
||||
if !engine.HardStopped() {
|
||||
t.Fatal("guardrail engine issued no decision for the run's agent stage: TaskContext.Guardrails is not wired to the engine the run was given")
|
||||
}
|
||||
}
|
||||
@@ -1,451 +0,0 @@
|
||||
package agentworker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/plugin"
|
||||
"github.com/samcharles93/archie-core/internal/storage"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
protocolmcp "github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
toolprovider "github.com/samcharles93/archie-core/internal/tools/provider"
|
||||
)
|
||||
|
||||
type fakeMCPEngine struct {
|
||||
id string
|
||||
entries []tools.ToolEntry
|
||||
startErr error
|
||||
discoverErr error
|
||||
stopErr error
|
||||
starts int
|
||||
discovers int
|
||||
stops int
|
||||
}
|
||||
|
||||
func (f *fakeMCPEngine) Manifest() plugin.Manifest {
|
||||
return plugin.Manifest{
|
||||
ID: "mcp." + f.id,
|
||||
Name: f.id,
|
||||
Version: "1.0.0",
|
||||
APIVersion: plugin.HostAPIVersion,
|
||||
Capabilities: []plugin.CapabilityKind{"tools"},
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeMCPEngine) Start(context.Context) error {
|
||||
f.starts++
|
||||
return f.startErr
|
||||
}
|
||||
|
||||
func (f *fakeMCPEngine) Discover(context.Context) ([]tools.ToolEntry, error) {
|
||||
f.discovers++
|
||||
return f.entries, f.discoverErr
|
||||
}
|
||||
|
||||
func (f *fakeMCPEngine) Stop(context.Context) error {
|
||||
f.stops++
|
||||
return f.stopErr
|
||||
}
|
||||
|
||||
func testTool(name string) tools.ToolEntry {
|
||||
return tools.ToolEntry{
|
||||
Name: name,
|
||||
Handler: func(context.Context, map[string]any) (any, error) {
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildMCPProviderSelectsTransport(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
server config.MCPServer
|
||||
wantTransport string
|
||||
wantType any
|
||||
wantCommand string
|
||||
wantArgs []string
|
||||
wantEnv []string
|
||||
wantEndpoint string
|
||||
wantMessageEndpoint string
|
||||
wantHeaders map[string]string
|
||||
wantErr string
|
||||
wantUnknown bool
|
||||
}{
|
||||
{
|
||||
name: "default stdio trims command",
|
||||
server: config.MCPServer{Name: " local ", Command: " server ", Args: []string{"--flag"}},
|
||||
wantTransport: "stdio",
|
||||
wantType: (*protocolmcp.StdioTransport)(nil),
|
||||
wantCommand: "server",
|
||||
wantArgs: []string{"--flag"},
|
||||
},
|
||||
{
|
||||
name: "explicit stdio",
|
||||
server: config.MCPServer{Name: "local", Transport: " STDIO ", Command: "server"},
|
||||
wantTransport: "stdio",
|
||||
wantType: (*protocolmcp.StdioTransport)(nil),
|
||||
wantCommand: "server",
|
||||
},
|
||||
{
|
||||
// Task containers are ephemeral, so an npx-launched MCP server
|
||||
// must be pointed at the shared mcp-npm cache volume mounted on
|
||||
// every container -- otherwise it re-resolves/re-downloads from
|
||||
// the registry on every single task.
|
||||
name: "npx stdio server gets the persistent npm cache",
|
||||
server: config.MCPServer{Name: "local", Command: "npx", Args: []string{"-y", "some-mcp-server"}},
|
||||
wantTransport: "stdio",
|
||||
wantType: (*protocolmcp.StdioTransport)(nil),
|
||||
wantCommand: "npx",
|
||||
wantArgs: []string{"-y", "some-mcp-server"},
|
||||
wantEnv: []string{
|
||||
"NPM_CONFIG_CACHE=" + storage.MCPNPMCacheMountDir,
|
||||
"NPM_CONFIG_PREFER_OFFLINE=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "non-npx stdio server gets no npm cache env",
|
||||
server: config.MCPServer{Name: "local", Command: "/usr/local/bin/my-mcp-server"},
|
||||
wantTransport: "stdio",
|
||||
wantType: (*protocolmcp.StdioTransport)(nil),
|
||||
wantCommand: "/usr/local/bin/my-mcp-server",
|
||||
},
|
||||
{
|
||||
name: "http",
|
||||
server: config.MCPServer{Name: "remote", Transport: "http", URL: " https://example.test/mcp ", Headers: map[string]string{"Authorization": "Bearer test"}},
|
||||
wantTransport: "http",
|
||||
wantType: (*protocolmcp.HTTPTransport)(nil),
|
||||
wantEndpoint: "https://example.test/mcp",
|
||||
wantHeaders: map[string]string{"Authorization": "Bearer test"},
|
||||
},
|
||||
{
|
||||
name: "streamable http alias",
|
||||
server: config.MCPServer{Name: "remote", Transport: "StreamableHTTP", URL: "https://example.test/mcp"},
|
||||
wantTransport: "streamablehttp",
|
||||
wantType: (*protocolmcp.HTTPTransport)(nil),
|
||||
wantEndpoint: "https://example.test/mcp",
|
||||
},
|
||||
{
|
||||
name: "sse",
|
||||
server: config.MCPServer{Name: "events", Transport: "sse", SSEEndpoint: " https://example.test/events ", MessageEndpoint: " https://example.test/messages ", Headers: map[string]string{"X-Test": "value"}},
|
||||
wantTransport: "sse",
|
||||
wantType: (*protocolmcp.SSETransport)(nil),
|
||||
wantEndpoint: "https://example.test/events",
|
||||
wantMessageEndpoint: "https://example.test/messages",
|
||||
wantHeaders: map[string]string{"X-Test": "value"},
|
||||
},
|
||||
{
|
||||
name: "stdio requires command",
|
||||
server: config.MCPServer{Name: "local", Transport: "stdio"},
|
||||
wantTransport: "stdio",
|
||||
wantErr: `MCP stdio server "local" requires a command`,
|
||||
},
|
||||
{
|
||||
name: "http requires url",
|
||||
server: config.MCPServer{Name: "remote", Transport: "http"},
|
||||
wantTransport: "http",
|
||||
wantErr: `MCP http server "remote" requires a url`,
|
||||
},
|
||||
{
|
||||
name: "sse requires endpoint",
|
||||
server: config.MCPServer{Name: "events", Transport: "sse"},
|
||||
wantTransport: "sse",
|
||||
wantErr: `MCP sse server "events" requires an sse_endpoint`,
|
||||
},
|
||||
{
|
||||
name: "unknown transport is a nonfatal skip",
|
||||
server: config.MCPServer{Name: "other", Transport: "websocket"},
|
||||
wantTransport: "websocket",
|
||||
wantErr: "unknown MCP transport: websocket",
|
||||
wantUnknown: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
provider, transportType, err := buildMCPProvider(tc.server, nil)
|
||||
if transportType != tc.wantTransport {
|
||||
t.Fatalf("transport = %q, want %q", transportType, tc.wantTransport)
|
||||
}
|
||||
if tc.wantErr != "" {
|
||||
if err == nil || err.Error() != tc.wantErr {
|
||||
t.Fatalf("error = %v, want %q", err, tc.wantErr)
|
||||
}
|
||||
if errors.Is(err, errUnknownMCPTransport) != tc.wantUnknown {
|
||||
t.Fatalf("errors.Is(err, errUnknownMCPTransport) = %v, want %v", errors.Is(err, errUnknownMCPTransport), tc.wantUnknown)
|
||||
}
|
||||
if provider != nil {
|
||||
t.Fatalf("provider = %T, want nil on invalid configuration", provider)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("buildMCPProvider() error = %v", err)
|
||||
}
|
||||
if provider == nil {
|
||||
t.Fatal("buildMCPProvider() returned nil provider")
|
||||
}
|
||||
transport := reflect.ValueOf(provider).Elem().FieldByName("transport")
|
||||
if transport.IsNil() {
|
||||
t.Fatal("provider transport is nil")
|
||||
}
|
||||
if got, want := transport.Elem().Type(), reflect.TypeOf(tc.wantType); got != want {
|
||||
t.Fatalf("transport type = %v, want %v", got, want)
|
||||
}
|
||||
assertMCPTransportConfig(t, transport.Elem(), tc.wantCommand, tc.wantArgs, tc.wantEnv, tc.wantEndpoint, tc.wantMessageEndpoint, tc.wantHeaders)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func assertMCPTransportConfig(
|
||||
t *testing.T,
|
||||
transport reflect.Value,
|
||||
wantCommand string,
|
||||
wantArgs []string,
|
||||
wantEnv []string,
|
||||
wantEndpoint string,
|
||||
wantMessageEndpoint string,
|
||||
wantHeaders map[string]string,
|
||||
) {
|
||||
t.Helper()
|
||||
config := transport.Elem().FieldByName("config")
|
||||
assertStringField := func(name, want string) {
|
||||
t.Helper()
|
||||
if want == "" {
|
||||
return
|
||||
}
|
||||
if got := config.FieldByName(name).String(); got != want {
|
||||
t.Errorf("transport config %s = %q, want %q", name, got, want)
|
||||
}
|
||||
}
|
||||
assertStringField("Command", wantCommand)
|
||||
if wantEndpoint != "" {
|
||||
field := "Endpoint"
|
||||
if config.FieldByName(field).Kind() == reflect.Invalid {
|
||||
field = "SSEEndpoint"
|
||||
}
|
||||
assertStringField(field, wantEndpoint)
|
||||
}
|
||||
assertStringField("MessageEndpoint", wantMessageEndpoint)
|
||||
|
||||
if wantArgs != nil {
|
||||
args := config.FieldByName("Args")
|
||||
got := make([]string, args.Len())
|
||||
for i := range args.Len() {
|
||||
got[i] = args.Index(i).String()
|
||||
}
|
||||
if !reflect.DeepEqual(got, wantArgs) {
|
||||
t.Errorf("transport config Args = %v, want %v", got, wantArgs)
|
||||
}
|
||||
}
|
||||
if wantHeaders != nil {
|
||||
headers := config.FieldByName("Headers")
|
||||
for key, want := range wantHeaders {
|
||||
if got := headers.MapIndex(reflect.ValueOf(key)).String(); got != want {
|
||||
t.Errorf("transport config Headers[%q] = %q, want %q", key, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Env only exists on StdioTransportConfig; other transports have no
|
||||
// registry-fetch dependency for this check to apply to.
|
||||
if envField := config.FieldByName("Env"); envField.Kind() != reflect.Invalid {
|
||||
got := make([]string, envField.Len())
|
||||
for i := range envField.Len() {
|
||||
got[i] = envField.Index(i).String()
|
||||
}
|
||||
if len(got) == 0 {
|
||||
got = nil
|
||||
}
|
||||
if !reflect.DeepEqual(got, wantEnv) {
|
||||
t.Errorf("transport config Env = %v, want %v", got, wantEnv)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartMCPProviderLifecycle(t *testing.T) {
|
||||
startErr := errors.New("start failed")
|
||||
discoverErr := errors.New("discover failed")
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
provider *fakeMCPEngine
|
||||
wantErr error
|
||||
wantTools int
|
||||
wantStarts int
|
||||
wantDiscovers int
|
||||
wantStops int
|
||||
wantRegistered []string
|
||||
}{
|
||||
{
|
||||
name: "start failure does not attempt discovery or stop",
|
||||
provider: &fakeMCPEngine{id: "start", startErr: startErr},
|
||||
wantErr: startErr,
|
||||
wantStarts: 1,
|
||||
},
|
||||
{
|
||||
name: "discovery failure stops started provider",
|
||||
provider: &fakeMCPEngine{id: "discover", discoverErr: discoverErr, stopErr: errors.New("ignored cleanup failure")},
|
||||
wantErr: discoverErr,
|
||||
wantStarts: 1,
|
||||
wantDiscovers: 1,
|
||||
wantStops: 1,
|
||||
},
|
||||
{
|
||||
name: "registration failure is nonfatal",
|
||||
provider: &fakeMCPEngine{id: "registration", entries: []tools.ToolEntry{
|
||||
testTool("available"),
|
||||
{Name: "invalid"},
|
||||
testTool("available"),
|
||||
}},
|
||||
wantTools: 3,
|
||||
wantStarts: 1,
|
||||
wantDiscovers: 1,
|
||||
wantRegistered: []string{"available"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
registry := tools.NewRegistry()
|
||||
gotTools, err := startMCPProvider(t.Context(), tc.name, tc.provider, registry, log)
|
||||
if !errors.Is(err, tc.wantErr) {
|
||||
t.Fatalf("error = %v, want %v", err, tc.wantErr)
|
||||
}
|
||||
if gotTools != tc.wantTools {
|
||||
t.Fatalf("tool count = %d, want %d", gotTools, tc.wantTools)
|
||||
}
|
||||
if tc.provider.starts != tc.wantStarts || tc.provider.discovers != tc.wantDiscovers || tc.provider.stops != tc.wantStops {
|
||||
t.Fatalf("lifecycle counts = start:%d discover:%d stop:%d, want start:%d discover:%d stop:%d", tc.provider.starts, tc.provider.discovers, tc.provider.stops, tc.wantStarts, tc.wantDiscovers, tc.wantStops)
|
||||
}
|
||||
for _, name := range tc.wantRegistered {
|
||||
if _, ok := registry.Get(name); !ok {
|
||||
t.Errorf("tool %q was not registered", name)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartMCPProvidersPreservesOptionalProviderBehavior(t *testing.T) {
|
||||
configErr := errors.New("invalid config")
|
||||
startErr := errors.New("start failed")
|
||||
discoverErr := errors.New("discover failed")
|
||||
stopErr := errors.New("stop failed")
|
||||
providers := map[string]*fakeMCPEngine{
|
||||
"start-failure": {id: "start-failure", startErr: startErr},
|
||||
"discover-failure": {id: "discover-failure", discoverErr: discoverErr},
|
||||
"valid-one": {id: "valid-one", entries: []tools.ToolEntry{testTool("shared")}, stopErr: stopErr},
|
||||
"valid-two": {id: "valid-two", entries: []tools.ToolEntry{testTool("shared")}},
|
||||
}
|
||||
buildCalls := make(map[string]int)
|
||||
build := func(server config.MCPServer, _ protocolmcp.SamplingHandler) (toolprovider.Engine, string, error) {
|
||||
buildCalls[server.Name]++
|
||||
switch server.Name {
|
||||
case "unknown":
|
||||
return nil, "websocket", fmt.Errorf("%w: websocket", errUnknownMCPTransport)
|
||||
case "invalid":
|
||||
return nil, "stdio", configErr
|
||||
default:
|
||||
return providers[server.Name], "stdio", nil
|
||||
}
|
||||
}
|
||||
|
||||
servers := []config.MCPServer{
|
||||
{Name: " "},
|
||||
{Name: "unknown"},
|
||||
{Name: "invalid"},
|
||||
{Name: "start-failure"},
|
||||
{Name: "discover-failure"},
|
||||
{Name: "valid-one"},
|
||||
{Name: "valid-two"},
|
||||
}
|
||||
set, err := startMCPProvidersWith(t.Context(), servers, nil, slog.New(slog.DiscardHandler), build)
|
||||
if err != nil {
|
||||
t.Fatalf("error = %v, want nil when valid providers remain available", err)
|
||||
}
|
||||
if set == nil {
|
||||
t.Fatal("provider set = nil, want valid providers to remain available")
|
||||
}
|
||||
if got := len(set.providers); got != 2 {
|
||||
t.Fatalf("available providers = %d, want 2", got)
|
||||
}
|
||||
if _, ok := set.registry.Get("shared"); !ok {
|
||||
t.Fatal("tool from valid provider was not available")
|
||||
}
|
||||
if buildCalls[" "] != 0 {
|
||||
t.Fatal("empty-name config reached provider builder")
|
||||
}
|
||||
if providers["start-failure"].stops != 0 {
|
||||
t.Fatal("start failure unexpectedly stopped provider")
|
||||
}
|
||||
if providers["discover-failure"].stops != 1 {
|
||||
t.Fatalf("discovery failure stop count = %d, want 1", providers["discover-failure"].stops)
|
||||
}
|
||||
|
||||
set.cleanup(t.Context(), slog.New(slog.DiscardHandler))
|
||||
if providers["valid-one"].stops != 1 || providers["valid-two"].stops != 1 {
|
||||
t.Fatalf("cleanup stop counts = (%d, %d), want (1, 1)", providers["valid-one"].stops, providers["valid-two"].stops)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartMCPProvidersReturnsNilWithoutAvailableProviders(t *testing.T) {
|
||||
firstErr := errors.New("first provider failed")
|
||||
secondErr := errors.New("second provider failed")
|
||||
tests := []struct {
|
||||
name string
|
||||
servers []config.MCPServer
|
||||
build mcpProviderBuilder
|
||||
wantErr error
|
||||
}{
|
||||
{
|
||||
name: "no configured servers",
|
||||
},
|
||||
{
|
||||
name: "unknown transport is skipped without error",
|
||||
servers: []config.MCPServer{{Name: "unknown"}},
|
||||
build: func(config.MCPServer, protocolmcp.SamplingHandler) (toolprovider.Engine, string, error) {
|
||||
return nil, "unknown", errUnknownMCPTransport
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "first provider error is returned",
|
||||
servers: []config.MCPServer{{Name: "first"}, {Name: "second"}},
|
||||
build: func(server config.MCPServer, _ protocolmcp.SamplingHandler) (toolprovider.Engine, string, error) {
|
||||
if server.Name == "first" {
|
||||
return nil, "stdio", firstErr
|
||||
}
|
||||
return nil, "stdio", secondErr
|
||||
},
|
||||
wantErr: firstErr,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
build := tc.build
|
||||
if build == nil {
|
||||
build = func(config.MCPServer, protocolmcp.SamplingHandler) (toolprovider.Engine, string, error) {
|
||||
t.Fatal("builder called without configured servers")
|
||||
return nil, "", nil
|
||||
}
|
||||
}
|
||||
set, err := startMCPProvidersWith(t.Context(), tc.servers, nil, slog.New(slog.DiscardHandler), build)
|
||||
if set != nil {
|
||||
t.Fatalf("provider set = %#v, want nil", set)
|
||||
}
|
||||
if tc.wantErr == nil {
|
||||
if err != nil {
|
||||
t.Fatalf("error = %v, want nil", err)
|
||||
}
|
||||
} else if reflect.ValueOf(err).Pointer() != reflect.ValueOf(tc.wantErr).Pointer() {
|
||||
t.Fatalf("error = %v, want exact first error %v", err, tc.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,193 +0,0 @@
|
||||
package agentworker
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
)
|
||||
|
||||
// capturedChatRequest is the JSON body the OpenAI-compatible provider sent for
|
||||
// the last call, which is where the max-token parameter is chosen.
|
||||
type capturedChatRequest struct {
|
||||
mu sync.Mutex
|
||||
body map[string]any
|
||||
}
|
||||
|
||||
func (c *capturedChatRequest) get() map[string]any {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.body
|
||||
}
|
||||
|
||||
// newCapturingChatAPI answers every completion and records the wire body, so a
|
||||
// test can assert the parameter the provider actually emitted rather than an
|
||||
// option the handler merely set.
|
||||
func newCapturingChatAPI(t *testing.T, capture *capturedChatRequest) *httptest.Server {
|
||||
t.Helper()
|
||||
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
capture.mu.Lock()
|
||||
capture.body = body
|
||||
capture.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = io.WriteString(w, `{"id":"chatcmpl-1","object":"chat.completion","created":1,"model":"test",`+
|
||||
`"choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],`+
|
||||
`"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`)
|
||||
}))
|
||||
t.Cleanup(api.Close)
|
||||
return api
|
||||
}
|
||||
|
||||
// newSamplingModelServer stands in for an OpenAI-compatible provider so a
|
||||
// sampling request can be answered without a real backend.
|
||||
func newSamplingModelServer(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = io.WriteString(w, `{"id":"chatcmpl-1","object":"chat.completion","created":1,"model":"gpt-5.6",`+
|
||||
`"choices":[{"index":0,"message":{"role":"assistant","content":"four"},"finish_reason":"stop"}],`+
|
||||
`"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`)
|
||||
}))
|
||||
t.Cleanup(api.Close)
|
||||
return api
|
||||
}
|
||||
|
||||
func testSamplingRequest() mcp.SamplingRequest {
|
||||
return mcp.SamplingRequest{
|
||||
Messages: []mcp.SamplingMessage{{
|
||||
Role: "user",
|
||||
Content: mcp.SamplingContent{Type: "text", Text: "2+2?"},
|
||||
}},
|
||||
MaxTokens: 16,
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskSamplingHandlerAnswersFromWorkerModel proves a task-scoped MCP
|
||||
// server's sampling request is answered by the worker's own model. A task
|
||||
// hosts the same configured MCP servers as a chat turn, so without this the
|
||||
// server is answered on the chat path and refused on the task path.
|
||||
func TestTaskSamplingHandlerAnswersFromWorkerModel(t *testing.T) {
|
||||
api := newSamplingModelServer(t)
|
||||
llm := agentexec.NewRuntime(map[string]agentexec.Provider{
|
||||
"openai": {Class: "openai", BaseURL: api.URL},
|
||||
})
|
||||
handler := taskSamplingHandler(llm, config.TaskConfig{Models: map[string]string{"builder": "openai/gpt-5.6"}})
|
||||
|
||||
result, err := handler(t.Context(), testSamplingRequest())
|
||||
if err != nil {
|
||||
t.Fatalf("sampling handler = %v, want a completion", err)
|
||||
}
|
||||
if result.Model != "openai/gpt-5.6" {
|
||||
t.Errorf("result.Model = %q, want the task's builder model", result.Model)
|
||||
}
|
||||
if result.Role != "assistant" || result.Content.Type != "text" || result.Content.Text != "four" {
|
||||
t.Errorf("result = %+v, want an assistant text completion", result)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskSamplingHandlerRefusesCleanly proves a worker with no usable model
|
||||
// answers the request with an error instead of panicking or dropping it: the
|
||||
// server sees a failed request, not a dead session.
|
||||
func TestTaskSamplingHandlerRefusesCleanly(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
llm bool
|
||||
model string
|
||||
want string
|
||||
}{
|
||||
{name: "no model runtime", llm: false, model: "openai/gpt-5.6", want: "no model runtime"},
|
||||
{name: "no builder model configured", llm: true, want: "no builder model"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
llm := agentexec.NewRuntime(nil)
|
||||
if tc.llm {
|
||||
llm = agentexec.NewRuntime(map[string]agentexec.Provider{"openai": {Class: "openai"}})
|
||||
}
|
||||
models := map[string]string{}
|
||||
if tc.model != "" {
|
||||
models["builder"] = tc.model
|
||||
}
|
||||
_, err := taskSamplingHandler(llm, config.TaskConfig{Models: models})(t.Context(), testSamplingRequest())
|
||||
if err == nil {
|
||||
t.Fatal("sampling handler returned no error with no usable model")
|
||||
}
|
||||
if !strings.Contains(err.Error(), tc.want) {
|
||||
t.Errorf("error = %q, want it to mention %q", err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskSamplingBoundFollowsModelClass proves the worker consumes the
|
||||
// reasoning flag carried in TaskConfig.ModelLimits: a reasoning-class builder
|
||||
// model gets no max-token bound (its provider rejects the max_tokens parameter
|
||||
// the chat-completions provider emits), while a classic model gets the
|
||||
// request's own bound.
|
||||
func TestTaskSamplingBoundFollowsModelClass(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
reasoning bool
|
||||
wantBound bool
|
||||
wantValue int
|
||||
}{
|
||||
{name: "reasoning model", reasoning: true},
|
||||
{name: "classic model", wantBound: true, wantValue: 16},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
capture := &capturedChatRequest{}
|
||||
api := newCapturingChatAPI(t, capture)
|
||||
llm := agentexec.NewRuntime(map[string]agentexec.Provider{
|
||||
"openai": {Class: "openai", BaseURL: api.URL},
|
||||
})
|
||||
cfg := config.TaskConfig{
|
||||
Models: map[string]string{"builder": "openai/gpt-5.6"},
|
||||
ModelLimits: map[string]config.ModelLimits{
|
||||
"openai/gpt-5.6": {MaxOutputTokens: 128000, Reasoning: tc.reasoning},
|
||||
},
|
||||
}
|
||||
if _, err := taskSamplingHandler(llm, cfg)(t.Context(), testSamplingRequest()); err != nil {
|
||||
t.Fatalf("sampling handler error = %v", err)
|
||||
}
|
||||
bound, present := capture.get()["max_tokens"]
|
||||
if present != tc.wantBound {
|
||||
t.Fatalf("request body max_tokens present = %v (value %v), want %v; body = %v", present, bound, tc.wantBound, capture.get())
|
||||
}
|
||||
if present && bound != float64(tc.wantValue) {
|
||||
t.Fatalf("request body max_tokens = %v, want %d; body = %v", bound, tc.wantValue, capture.get())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildMCPProviderWiresTaskSamplingHandler proves the worker's MCP
|
||||
// provider builder hands the provider the sampling handler, so the seam a task
|
||||
// run builds providers through is the one that answers sampling -- not only
|
||||
// the handler in isolation.
|
||||
func TestBuildMCPProviderWiresTaskSamplingHandler(t *testing.T) {
|
||||
handler := taskSamplingHandler(agentexec.NewRuntime(map[string]agentexec.Provider{
|
||||
"openai": {Class: "openai"},
|
||||
}), config.TaskConfig{Models: map[string]string{"builder": "openai/gpt-5.6"}})
|
||||
|
||||
provider, _, err := buildMCPProvider(config.MCPServer{Name: "sampling", Command: "server"}, handler)
|
||||
if err != nil {
|
||||
t.Fatalf("buildMCPProvider: %v", err)
|
||||
}
|
||||
field := reflect.ValueOf(provider).Elem().FieldByName("samplingHandler")
|
||||
if field.IsNil() {
|
||||
t.Fatal("task MCP provider carries no sampling handler: a task-scoped server's sampling/createMessage request is refused")
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package agentworker
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
)
|
||||
|
||||
// TestArchieAgentMCPOverStdio drives the real archie-agent binary's mcp
|
||||
// subcommand with the MCP SDK's client, the way a harness CLI does.
|
||||
func TestArchieAgentMCPOverStdio(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
bin := filepath.Join(dir, "archie-agent")
|
||||
build := exec.CommandContext(t.Context(), "go", "build", "-o", bin, "github.com/samcharles93/archie-core/cmd/archie-agent")
|
||||
if out, err := build.CombinedOutput(); err != nil {
|
||||
t.Fatalf("build archie-agent: %v\n%s", err, out)
|
||||
}
|
||||
spec, _ := json.Marshal([]agentexec.CaptureTool{{
|
||||
Name: "record_finding", Description: "Record one finding.",
|
||||
Parameters: json.RawMessage(`{"type":"object","properties":{"title":{"type":"string"}},"required":["title"]}`),
|
||||
RequiredFields: []string{"title"},
|
||||
}})
|
||||
specPath, captures := filepath.Join(dir, "tools.json"), filepath.Join(dir, "captures.jsonl")
|
||||
if err := os.WriteFile(specPath, spec, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(captures, nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
transport := &mcp.CommandTransport{Command: exec.CommandContext(t.Context(), bin, "mcp", "-spec", specPath, "-captures", captures)}
|
||||
session, err := mcp.NewClient(&mcp.Implementation{Name: "harness", Version: "0"}, nil).Connect(t.Context(), transport, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer session.Close()
|
||||
res, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: "record_finding", Arguments: map[string]any{"title": "nil deref"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if text, ok := res.Content[0].(*mcp.TextContent); !ok || !strings.Contains(text.Text, "recorded") {
|
||||
t.Fatalf("reply %+v", res.Content)
|
||||
}
|
||||
_ = session.Close()
|
||||
raw, err := os.ReadFile(captures)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(raw), `"title":"nil deref"`) {
|
||||
t.Fatalf("captures file %q, want the recorded call", raw)
|
||||
}
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
package agentworker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
)
|
||||
|
||||
type persistentRunnerFunc func(context.Context, string, agentexec.Request, agentexec.ToolCallReporter) (agentexec.Result, error)
|
||||
|
||||
func (f persistentRunnerFunc) Run(ctx context.Context, workspace string, request agentexec.Request, report agentexec.ToolCallReporter) (agentexec.Result, error) {
|
||||
return f(ctx, workspace, request, report)
|
||||
}
|
||||
|
||||
func TestPersistentRunnerRecordsStageMemoryAndPluginOverride(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
pluginsDir := filepath.Join(dir, "plugins")
|
||||
if err := os.MkdirAll(pluginsDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(pluginsDir, "check.go"), []byte("override"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
runner := persistentRunner{
|
||||
Runner: persistentRunnerFunc(func(_ context.Context, _ string, request agentexec.Request, _ agentexec.ToolCallReporter) (agentexec.Result, error) {
|
||||
if got := request.Plugins[0].Src; got != "override" {
|
||||
t.Fatalf("plugin source = %q, want persistent override", got)
|
||||
}
|
||||
return agentexec.Result{Version: agentexec.ProtocolVersion, TaskID: request.TaskID, Attempt: request.Attempt, Stage: request.Stage, Status: agentexec.StatusPassed, AppendedNotes: []string{"remember me"}}, nil
|
||||
}),
|
||||
enabled: true,
|
||||
sessionPath: filepath.Join(dir, "session.jsonl"),
|
||||
memoryPath: filepath.Join(dir, "memory.jsonl"),
|
||||
pluginsDir: pluginsDir,
|
||||
}
|
||||
_, err := runner.Run(context.Background(), t.TempDir(), agentexec.Request{
|
||||
TaskID: 7, Attempt: 2, Stage: "implement",
|
||||
Plugins: []agentexec.PluginSpec{{Name: "check", Src: "bundled"}},
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, path := range []string{runner.sessionPath, runner.memoryPath} {
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasSuffix(string(content), "\n") {
|
||||
t.Errorf("%s is not newline-terminated JSONL", path)
|
||||
}
|
||||
}
|
||||
memory, err := os.ReadFile(runner.memoryPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(memory), `"content":"remember me"`) {
|
||||
t.Errorf("memory record = %s, want appended note", memory)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadProjectMemoryRestoresEarlierNotes(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "memory.jsonl")
|
||||
if err := os.WriteFile(path, []byte("{\"content\":\"first fact\"}\n{\"content\":\"second fact\"}\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := readProjectMemory(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, fact := range []string{"first fact", "second fact"} {
|
||||
if !strings.Contains(got, fact) {
|
||||
t.Errorf("memory prompt %q missing %q", got, fact)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadProjectMemoryAcceptsLargePersistedNote(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "memory.jsonl")
|
||||
note := strings.Repeat("x", 70*1024)
|
||||
encoded := `{"content":"` + note + `"}` + "\n"
|
||||
if err := os.WriteFile(path, []byte(encoded), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := readProjectMemory(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(got, note) {
|
||||
t.Error("large persisted note was not restored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPersistentRunnerRejectsFailedResultBeforePersistence(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
runner := persistentRunner{
|
||||
Runner: persistentRunnerFunc(func(_ context.Context, _ string, _ agentexec.Request, _ agentexec.ToolCallReporter) (agentexec.Result, error) {
|
||||
return agentexec.Result{AppendedNotes: []string{"untrusted"}}, os.ErrPermission
|
||||
}),
|
||||
enabled: true,
|
||||
sessionPath: filepath.Join(dir, "session.jsonl"),
|
||||
memoryPath: filepath.Join(dir, "memory.jsonl"),
|
||||
pluginsDir: filepath.Join(dir, "plugins"),
|
||||
}
|
||||
_, err := runner.Run(context.Background(), t.TempDir(), agentexec.Request{}, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected runner error")
|
||||
}
|
||||
for _, path := range []string{runner.sessionPath, runner.memoryPath} {
|
||||
if _, statErr := os.Stat(path); !os.IsNotExist(statErr) {
|
||||
t.Errorf("%s persisted rejected output", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package agentworker
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
@@ -1,90 +0,0 @@
|
||||
package agentworker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func echoTarget(t *testing.T, reply string) string {
|
||||
t.Helper()
|
||||
ln, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = ln.Close() })
|
||||
go func() {
|
||||
for {
|
||||
c, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(c, reply)
|
||||
_ = c.Close()
|
||||
}
|
||||
}()
|
||||
return ln.Addr().String()
|
||||
}
|
||||
|
||||
func freeAddr(t *testing.T) string {
|
||||
t.Helper()
|
||||
ln, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
addr := ln.Addr().String()
|
||||
_ = ln.Close()
|
||||
return addr
|
||||
}
|
||||
|
||||
func TestRunRelayForwardsEachListenerToItsTarget(t *testing.T) {
|
||||
proxy, nats := freeAddr(t), freeAddr(t)
|
||||
forwards := map[string]string{proxy: echoTarget(t, "proxy"), nats: echoTarget(t, "nats")}
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- RunRelay(ctx, forwards) }()
|
||||
|
||||
for listen, want := range map[string]string{proxy: "proxy", nats: "nats"} {
|
||||
var got []byte
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
c, err := (&net.Dialer{}).DialContext(t.Context(), "tcp", listen)
|
||||
if err == nil {
|
||||
_ = c.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
got, _ = io.ReadAll(c)
|
||||
_ = c.Close()
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("relay never listened on %s: %v", listen, err)
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
if string(got) != want {
|
||||
t.Fatalf("%s reached %q, want %q", listen, got, want)
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("RunRelay after cancel: %v", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("RunRelay did not stop on cancel")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRelayFailsWhenAListenerCannotBind(t *testing.T) {
|
||||
taken, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer taken.Close()
|
||||
err = RunRelay(t.Context(), map[string]string{taken.Addr().String(): "127.0.0.1:1", freeAddr(t): "127.0.0.1:1"})
|
||||
if err == nil {
|
||||
t.Fatal("RunRelay started with a listener that could not bind")
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
package agentworker
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
|
||||
)
|
||||
|
||||
// stepVocabularyProbe is a provider set of one, used only to prove the
|
||||
// manager a root builds is live: registering through it must reach its
|
||||
// vocabulary.
|
||||
type stepVocabularyProbe struct{}
|
||||
|
||||
func (stepVocabularyProbe) Name() string { return "probe" }
|
||||
|
||||
func (stepVocabularyProbe) StepTypes() []workflow.StepType {
|
||||
return []workflow.StepType{{Name: "probe.registered", Factory: func(yaml.Node) (workflow.Stage, error) {
|
||||
return workflow.Stage{Name: "probe.registered"}, nil
|
||||
}}}
|
||||
}
|
||||
|
||||
// TestProductionWorkerDependenciesRegisterTheSharedStepVocabulary pins the
|
||||
// executing side's composition root. productionWorkerDependencies is reached
|
||||
// only by Run, so nothing else fails if it stops registering the shared
|
||||
// provider set (internal/infrastructure/workflowsteps) and hands the worker a
|
||||
// manager with no shipped stage: every compile then fails at run time, in a
|
||||
// container, per task.
|
||||
func TestProductionWorkerDependenciesRegisterTheSharedStepVocabulary(t *testing.T) {
|
||||
dependencies, err := productionWorkerDependencies()
|
||||
if err != nil {
|
||||
t.Fatalf("productionWorkerDependencies: %v", err)
|
||||
}
|
||||
requireSharedStepVocabulary(t, dependencies.steps)
|
||||
}
|
||||
|
||||
// requireSharedStepVocabulary holds a composition root's manager to both halves
|
||||
// of the contract: it resolves the shipped vocabulary, and it is live enough to
|
||||
// take a provider registered through it.
|
||||
func requireSharedStepVocabulary(t *testing.T, steps *workflow.Manager) {
|
||||
t.Helper()
|
||||
if steps == nil {
|
||||
t.Fatal("the composition root registered no workflow step vocabulary")
|
||||
}
|
||||
got := steps.StepTypes()
|
||||
// Containment, not equality: adding a provider to the shared set
|
||||
// (workflowsteps.Providers) is the documented way a step type arrives, and
|
||||
// that must not have to edit this guard. What it holds is that the shipped
|
||||
// stages are all present, which is what a root regressing to
|
||||
// workflow.NewManager() loses.
|
||||
for name := range workflow.BuiltinStepRegistry() {
|
||||
if !slices.Contains(got, name) {
|
||||
t.Errorf("the composition root resolves %v, which is missing the shipped stage %q", got, name)
|
||||
}
|
||||
}
|
||||
// The other half is provenance: every name the root resolves must be
|
||||
// declared by the shared provider set, not by a near-identical provider of
|
||||
// the root's own, because that set is what ties this process's vocabulary to
|
||||
// the State Store that validates against it. It is content, not identity --
|
||||
// the shipped provider rebuilds its factories on every call.
|
||||
declared := sharedStepTypeNames()
|
||||
for _, name := range got {
|
||||
if !slices.Contains(declared, name) {
|
||||
t.Errorf("the composition root resolves %q, which no provider in the shared set declares", name)
|
||||
}
|
||||
}
|
||||
if err := steps.Register(stepVocabularyProbe{}); err != nil {
|
||||
t.Fatalf("register a provider through the root's manager: %v", err)
|
||||
}
|
||||
if _, resolved := steps.Registry()["probe.registered"]; !resolved {
|
||||
t.Fatal("a provider registered through the root's manager did not reach its vocabulary")
|
||||
}
|
||||
}
|
||||
|
||||
// sharedStepTypeNames returns the step types the shared provider set declares,
|
||||
// read through the same Providers() seam the composition roots register.
|
||||
func sharedStepTypeNames() []string {
|
||||
names := make([]string, 0)
|
||||
for _, provider := range workflowsteps.Providers() {
|
||||
for _, stepType := range provider.StepTypes() {
|
||||
names = append(names, stepType.Name)
|
||||
}
|
||||
}
|
||||
slices.Sort(names)
|
||||
return names
|
||||
}
|
||||
@@ -1,994 +0,0 @@
|
||||
package agentworker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-git/go-git/v6"
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
natssrv "github.com/nats-io/nats-server/v2/test"
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/forgerpc"
|
||||
agentnats "github.com/samcharles93/archie-core/internal/infrastructure/agenttransport/nats"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
|
||||
"github.com/samcharles93/archie-core/internal/installtype"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
"github.com/samcharles93/archie-core/internal/worktreerpc"
|
||||
)
|
||||
|
||||
// testSteps builds the production workflow step vocabulary for tests that are
|
||||
// not about the vocabulary itself (the composition-level agreement test in
|
||||
// internal/app/controlplane is).
|
||||
func testSteps(t *testing.T) *workflow.Manager {
|
||||
t.Helper()
|
||||
steps, err := workflowsteps.NewManager()
|
||||
if err != nil {
|
||||
t.Fatalf("build workflow step vocabulary: %v", err)
|
||||
}
|
||||
return steps
|
||||
}
|
||||
|
||||
// ── regression: archie-core#520 -- worktree ownership must be
|
||||
// reconciled before push, since the agent commits as root inside the
|
||||
// container and the daemon reads those same loose objects as its own
|
||||
// non-root host user ──────────────────────────────────────────────────
|
||||
|
||||
type fakePushTrees struct {
|
||||
pushed bool
|
||||
pushErr error
|
||||
}
|
||||
|
||||
func (f *fakePushTrees) Push(context.Context) error {
|
||||
f.pushed = true
|
||||
return f.pushErr
|
||||
}
|
||||
|
||||
func TestWorktreeOwnerIDParsesEnvValue(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
env string
|
||||
want int
|
||||
}{
|
||||
{"unset", "", -1},
|
||||
{"zero is a valid uid (root)", "0", 0},
|
||||
{"typical non-root uid", "1000", 1000},
|
||||
{"garbage falls back to unset", "not-a-number", -1},
|
||||
{"negative falls back to unset", "-1", -1},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := worktreeOwnerID(c.env); got != c.want {
|
||||
t.Errorf("worktreeOwnerID(%q) = %d, want %d", c.env, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestHybridTreesPushReconcilesOwnershipWhenConfigured chowns to the test
|
||||
// process's own uid/gid -- a permission no-op that succeeds without root --
|
||||
// so this proves the walk runs and still reaches the underlying push,
|
||||
// without needing privilege to chown to an arbitrary owner.
|
||||
func TestHybridTreesPushReconcilesOwnershipWhenConfigured(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "file.txt"), []byte("x"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Join(dir, "sub"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "sub", "nested.txt"), []byte("y"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
fake := &fakePushTrees{}
|
||||
trees := &hybridTrees{
|
||||
push: fake,
|
||||
localDir: dir,
|
||||
worktreeUID: os.Getuid(),
|
||||
worktreeGID: os.Getgid(),
|
||||
}
|
||||
|
||||
if err := trees.Push(t.Context(), dir, "branch"); err != nil {
|
||||
t.Fatalf("Push: %v", err)
|
||||
}
|
||||
if !fake.pushed {
|
||||
t.Fatal("Push did not reach the underlying remote push")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHybridTreesPushReconcilesOwnershipWithDanglingSymlink: a repo can
|
||||
// legitimately track a symlink whose target doesn't exist inside the
|
||||
// container (e.g. a relative link to something outside the checkout, or to
|
||||
// a tool the image doesn't ship). Chowning must not follow it -- a
|
||||
// following chown fails on a dangling target, which would abort a push
|
||||
// that would otherwise have succeeded, a regression worse than the bug
|
||||
// being fixed here.
|
||||
func TestHybridTreesPushReconcilesOwnershipWithDanglingSymlink(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.Symlink(filepath.Join(dir, "does-not-exist"), filepath.Join(dir, "broken-link")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
fake := &fakePushTrees{}
|
||||
trees := &hybridTrees{
|
||||
push: fake,
|
||||
localDir: dir,
|
||||
worktreeUID: os.Getuid(),
|
||||
worktreeGID: os.Getgid(),
|
||||
}
|
||||
|
||||
if err := trees.Push(t.Context(), dir, "branch"); err != nil {
|
||||
t.Fatalf("Push: %v", err)
|
||||
}
|
||||
if !fake.pushed {
|
||||
t.Fatal("Push did not reach the underlying remote push")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHybridTreesPushSkipsReconciliationWhenNotConfigured: an unset
|
||||
// WORKTREE_UID/GID (archie-core's non-container and test callers) must not
|
||||
// attempt any chown at all -- a nonexistent dir would otherwise fail the
|
||||
// walk, so this proves the walk is skipped entirely, not just tolerant of
|
||||
// this one input.
|
||||
func TestHybridTreesPushSkipsReconciliationWhenNotConfigured(t *testing.T) {
|
||||
fake := &fakePushTrees{}
|
||||
trees := &hybridTrees{
|
||||
push: fake,
|
||||
localDir: filepath.Join(t.TempDir(), "does-not-exist"),
|
||||
worktreeUID: -1,
|
||||
worktreeGID: -1,
|
||||
}
|
||||
|
||||
if err := trees.Push(t.Context(), trees.localDir, "branch"); err != nil {
|
||||
t.Fatalf("Push: %v", err)
|
||||
}
|
||||
if !fake.pushed {
|
||||
t.Fatal("Push did not reach the underlying remote push")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHybridTreesPrepareResolvesTheTargetBranch pins the container half of the
|
||||
// workflow prepare seam: the daemon has already positioned the bind-mounted
|
||||
// worktree, so the adapter resolves its directory and returns the requested
|
||||
// resume target verbatim -- the branch a remediation continues -- while a fresh
|
||||
// prepare returns the branch the daemon persisted on the task row.
|
||||
func TestHybridTreesPrepareResolvesTheTargetBranch(t *testing.T) {
|
||||
trees := &hybridTrees{localDir: "/work/issue-1", branch: "archie/fresh"}
|
||||
|
||||
dir, branch, err := trees.Prepare(t.Context(), "o", "r", "main", 1, "title", "", "", workflow.PrepareTarget("archie/pr-branch"))
|
||||
if err != nil {
|
||||
t.Fatalf("Prepare(resume): %v", err)
|
||||
}
|
||||
if dir != "/work/issue-1" || branch != "archie/pr-branch" {
|
||||
t.Fatalf("Prepare(resume) = %q/%q, want /work/issue-1/archie/pr-branch", dir, branch)
|
||||
}
|
||||
|
||||
dir, branch, err = trees.Prepare(t.Context(), "o", "r", "main", 1, "title", "", "", workflow.PrepareFresh)
|
||||
if err != nil {
|
||||
t.Fatalf("Prepare(fresh): %v", err)
|
||||
}
|
||||
if dir != "/work/issue-1" || branch != "archie/fresh" {
|
||||
t.Fatalf("Prepare(fresh) = %q/%q, want /work/issue-1/archie/fresh", dir, branch)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHybridTreesCommitReconcilesOwnershipEvenWhenCommitFails(t *testing.T) {
|
||||
missing := filepath.Join(t.TempDir(), "does-not-exist")
|
||||
trees := &hybridTrees{
|
||||
local: &worktree.Manager{},
|
||||
localDir: missing,
|
||||
worktreeUID: os.Getuid(),
|
||||
worktreeGID: os.Getgid(),
|
||||
}
|
||||
|
||||
_, err := trees.CommitAll(t.Context(), missing, "test commit")
|
||||
if err == nil {
|
||||
t.Fatal("CommitAll error = nil, want commit and ownership reconciliation failure")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "reconcile worktree ownership after commit") {
|
||||
t.Fatalf("CommitAll error = %q, want ownership reconciliation context", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHybridTreesPushSurfacesOwnershipReconciliationFailure: a configured
|
||||
// but broken reconciliation (the dir push is asked to fix vanished) must
|
||||
// fail loudly rather than forward to a push that will only fail later with
|
||||
// a much more confusing git-internal permission error.
|
||||
func TestHybridTreesPushSurfacesOwnershipReconciliationFailure(t *testing.T) {
|
||||
fake := &fakePushTrees{}
|
||||
missing := filepath.Join(t.TempDir(), "does-not-exist")
|
||||
trees := &hybridTrees{
|
||||
push: fake,
|
||||
localDir: missing,
|
||||
worktreeUID: os.Getuid(),
|
||||
worktreeGID: os.Getgid(),
|
||||
}
|
||||
|
||||
err := trees.Push(t.Context(), missing, "branch")
|
||||
if err == nil {
|
||||
t.Fatal("expected an error reconciling ownership of a missing directory")
|
||||
}
|
||||
if fake.pushed {
|
||||
t.Fatal("Push must not reach the underlying remote push when reconciliation fails")
|
||||
}
|
||||
}
|
||||
|
||||
// TestApplyToolLimitsWiresConfiguredPolicyIntoLoopRunner guards against
|
||||
// regressing archie-core's tool-result cap and spill dir back to inert
|
||||
// zero values on the worker path (agentexec-1 / tools-core-11): a
|
||||
// *LoopRunner built for a task must carry the daemon's configured
|
||||
// ToolPolicy, not the zero value NewLoopRunner leaves it at.
|
||||
func TestApplyToolLimitsWiresConfiguredPolicyIntoLoopRunner(t *testing.T) {
|
||||
runner := agentexec.NewLoopRunner(agentexec.NewRuntime(nil), slog.New(slog.DiscardHandler))
|
||||
policy := config.ToolPolicy{MaxResultChars: 12345, SpillDir: "/var/tmp/archie-spill"}
|
||||
|
||||
applyToolLimits(runner, policy, []string{"whois"})
|
||||
|
||||
want := agentexec.ToolLimits{MaxResultChars: 12345, SpillDir: "/var/tmp/archie-spill"}
|
||||
if runner.Limits != want {
|
||||
t.Fatalf("runner.Limits = %+v, want %+v", runner.Limits, want)
|
||||
}
|
||||
if len(runner.AllowTools) != 1 || runner.AllowTools[0] != "whois" {
|
||||
t.Fatalf("runner.AllowTools = %v, want the profile's allowlist", runner.AllowTools)
|
||||
}
|
||||
}
|
||||
|
||||
// TestApplyToolLimitsIgnoresNonLoopRunner confirms a test-fake runner (which
|
||||
// is not a *agentexec.LoopRunner) is left untouched rather than panicking.
|
||||
func TestApplyToolLimitsIgnoresNonLoopRunner(t *testing.T) {
|
||||
applyToolLimits(panicRunner{t}, config.ToolPolicy{MaxResultChars: 1}, nil)
|
||||
}
|
||||
|
||||
type panicRunner struct{ t *testing.T }
|
||||
|
||||
func (r panicRunner) Run(context.Context, string, agentexec.Request, agentexec.ToolCallReporter) (agentexec.Result, error) {
|
||||
r.t.Fatal("bootstrap workflow must not invoke an LLM runner")
|
||||
return agentexec.Result{}, nil
|
||||
}
|
||||
|
||||
type prCapturingForge struct {
|
||||
prs []struct{ owner, repo, title, head, base, body string }
|
||||
}
|
||||
|
||||
func (f *prCapturingForge) Comment(context.Context, string, string, int, string) (int64, error) {
|
||||
return 1, nil
|
||||
}
|
||||
|
||||
func (f *prCapturingForge) CloseIssue(context.Context, string, string, int, string) error { return nil }
|
||||
|
||||
func (f *prCapturingForge) CreatePR(_ context.Context, owner, repo, title, head, base, body string) (int, error) {
|
||||
f.prs = append(f.prs, struct{ owner, repo, title, head, base, body string }{owner, repo, title, head, base, body})
|
||||
return 5, nil
|
||||
}
|
||||
func (f *prCapturingForge) SetStateLabel(context.Context, string, string, int, string, []string) {}
|
||||
func (f *prCapturingForge) AcceptInvitations(context.Context) error { panic("unexpected call") }
|
||||
|
||||
func (f *prCapturingForge) AssignedIssues(context.Context, string, string, string) ([]forge.Issue, error) {
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
func (f *prCapturingForge) IssuesWithLabel(context.Context, string, string, string) ([]forge.Issue, error) {
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
func (f *prCapturingForge) PRState(context.Context, string, string, int) (string, error) {
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
func (f *prCapturingForge) CreateIssue(context.Context, string, string, string, string, []string) (int, error) {
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
func (f *prCapturingForge) React(context.Context, string, string, int, string) error {
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
func (f *prCapturingForge) VerifyPush(context.Context, string, string) error {
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
func (f *prCapturingForge) LinkBranch(context.Context, string, string, int, string) error { return nil }
|
||||
|
||||
func (f *prCapturingForge) CreateReviewComments(context.Context, string, string, int, string, []workflow.ReviewComment) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *prCapturingForge) ReplyToReview(context.Context, string, string, int, int64, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type remoteManager struct {
|
||||
manager *worktree.Manager
|
||||
dir string
|
||||
branch string
|
||||
}
|
||||
|
||||
func (r *remoteManager) Prepare(ctx context.Context, owner, repo, base string, issue int, title, body, labels string, target workflow.PrepareTarget) (string, string, error) {
|
||||
dir, branch, err := r.manager.Prepare(ctx, owner, repo, base, issue, title, body, labels, worktree.Target(target))
|
||||
if err == nil {
|
||||
r.dir = dir
|
||||
r.branch = branch
|
||||
}
|
||||
return dir, branch, err
|
||||
}
|
||||
|
||||
func (r *remoteManager) Push(ctx context.Context) error {
|
||||
return r.manager.Push(ctx, r.dir, r.branch)
|
||||
}
|
||||
|
||||
func newLocalRemote(t *testing.T, owner, repo string) string {
|
||||
t.Helper()
|
||||
host := t.TempDir()
|
||||
bare := filepath.Join(host, owner, repo+".git")
|
||||
seed := filepath.Join(t.TempDir(), "seed")
|
||||
run := func(dir string, args ...string) {
|
||||
t.Helper()
|
||||
cmd := exec.CommandContext(t.Context(), "git", args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0")
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("git %v: %v\n%s", args, err, out)
|
||||
}
|
||||
}
|
||||
if err := os.MkdirAll(bare, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run(host, "init", "--bare", "-b", "main", bare)
|
||||
if err := os.MkdirAll(seed, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run(seed, "init", "-b", "main")
|
||||
run(seed, "config", "user.name", "seeder")
|
||||
run(seed, "config", "user.email", "seed@example.com")
|
||||
run(seed, "config", "commit.gpgsign", "false")
|
||||
if err := os.WriteFile(filepath.Join(seed, "README.md"), []byte("seed\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run(seed, "add", "-A")
|
||||
run(seed, "commit", "-m", "seed")
|
||||
run(seed, "push", "file://"+bare, "main")
|
||||
return host
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// TestNewLocalRemoteIgnoresHostSigningConfig pins the fixture's hermeticity:
|
||||
// it must not depend on the developer's global git identity or a signing agent.
|
||||
func TestNewLocalRemoteIgnoresHostSigningConfig(t *testing.T) {
|
||||
t.Setenv("GIT_CONFIG_GLOBAL", hostileSigningConfig(t))
|
||||
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
|
||||
newLocalRemote(t, "acme", "todo")
|
||||
}
|
||||
|
||||
func startEmbeddedTaskRPCServer(t *testing.T) *server.Server {
|
||||
t.Helper()
|
||||
srv := natssrv.RunRandClientPortServer()
|
||||
t.Cleanup(srv.Shutdown)
|
||||
if err := srv.EnableJetStream(&server.JetStreamConfig{StoreDir: t.TempDir()}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return srv
|
||||
}
|
||||
|
||||
func connectTaskRPC(t *testing.T, url string) *natsio.Conn {
|
||||
t.Helper()
|
||||
connection, err := natsio.Connect(url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(connection.Close)
|
||||
return connection
|
||||
}
|
||||
|
||||
// startStateStoreGRPC serves the State Store gRPC contract over a loopback
|
||||
// TCP listener fronting local, returning the dial address. The agent is fully
|
||||
// on gRPC for its store calls (docs/prds/state-store-contract.md §12 step 4),
|
||||
// so an agentworker test that drives executeTaskRequest needs a real State
|
||||
// Store server rather than the deleted NATS storerpc path.
|
||||
func startStateStoreGRPC(t *testing.T, local *pgstore.TaskDB) string {
|
||||
t.Helper()
|
||||
listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := grpc.NewServer()
|
||||
eda := pgstore.EDA(t, nil)
|
||||
staterpc.RegisterServer(server, staterpc.Deps{
|
||||
Tasks: local, Captures: eda, Mappings: eda, Bindings: eda,
|
||||
BindingDispatcher: eda, BindingTaskCreator: local, WorkflowCalls: local,
|
||||
Steps: local, Canceller: local,
|
||||
})
|
||||
go func() { _ = server.Serve(listener) }()
|
||||
t.Cleanup(func() { server.Stop(); _ = listener.Close() })
|
||||
return listener.Addr().String()
|
||||
}
|
||||
|
||||
func TestRunTaskExecutesBootstrapWorkflowEndToEnd(t *testing.T) {
|
||||
if _, err := exec.LookPath("git"); err != nil {
|
||||
t.Skip("git not installed")
|
||||
}
|
||||
ctx := t.Context()
|
||||
host := newLocalRemote(t, "acme", "widget")
|
||||
st := pgstore.Open(t)
|
||||
if _, err := st.EnqueueIssue(ctx, "acme", "widget", 1, "feat: bootstrap test", "", "bootstrap", ""); err != nil {
|
||||
t.Fatalf("enqueue: %v", err)
|
||||
}
|
||||
task, err := st.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("claim: (%v, %v)", task, err)
|
||||
}
|
||||
fg := &prCapturingForge{}
|
||||
manager := &worktree.Manager{WorkDir: t.TempDir(), Token: "unused", BotUser: "archie-bot", BotEmail: "archie-bot@example.com", BaseURL: "file://" + host}
|
||||
remote := &remoteManager{manager: manager}
|
||||
hostDir, _, err := remote.Prepare(ctx, "acme", "widget", "main", 1, task.Title, "", "bootstrap", workflow.PrepareFresh)
|
||||
if err != nil {
|
||||
t.Fatalf("prepare: %v", err)
|
||||
}
|
||||
req := taskrun.Request{
|
||||
Task: task,
|
||||
Repo: config.Repo{Owner: "acme", Name: "widget", Base: "main"},
|
||||
Cfg: config.Config{BotUser: "archie-bot", BotEmail: "archie-bot@example.com"}.ForTask(),
|
||||
}
|
||||
fakeRunner := runnerFactory(func(map[string]agentexec.Provider, *slog.Logger) agentexec.Runner { return panicRunner{t} })
|
||||
response, err := runTask(ctx, req, taskDependencies{forge: fg, store: st, trees: remote, steps: testSteps(t)}, fakeRunner, hostDir, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatalf("runTask: %v", err)
|
||||
}
|
||||
if response.Status != workflow.StatusPROpen || len(fg.prs) != 1 {
|
||||
t.Fatalf("response status/PRs = (%q, %d), want (%q, 1)", response.Status, len(fg.prs), workflow.StatusPROpen)
|
||||
}
|
||||
stored, err := st.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
if err != nil || stored == nil || stored.Status != workflow.StatusPROpen || stored.PRNumber != 5 {
|
||||
t.Fatalf("stored task = (%+v, %v), want PR-open task #5", stored, err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(hostDir, ".archie", "bootstrap.md")); err != nil {
|
||||
t.Fatalf("expected bootstrap marker file: %v", err)
|
||||
}
|
||||
repo, err := git.PlainOpen(hostDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
head, err := repo.Head()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
commit, err := repo.CommitObject(head.Hash())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if commit.Author.Name != "archie-bot" || commit.Author.Email != "archie-bot@example.com" ||
|
||||
commit.Committer.Name != "archie-bot" || commit.Committer.Email != "archie-bot@example.com" {
|
||||
t.Fatalf("commit identity = author %q <%s>, committer %q <%s>",
|
||||
commit.Author.Name, commit.Author.Email, commit.Committer.Name, commit.Committer.Email)
|
||||
}
|
||||
|
||||
// The change the run produced is captured at the push, through the
|
||||
// container's hybridTrees, and persisted as durable provenance attributed
|
||||
// to the attempt -- and captured once more by OpenPR, the first moment a
|
||||
// capture can carry the pull-request number the view links. This is the
|
||||
// only end-to-end path that matters: every production workflow.Run executes
|
||||
// here.
|
||||
timeline, err := st.TaskEvents(ctx, task.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskEvents: %v", err)
|
||||
}
|
||||
var captured []events.Event
|
||||
for _, e := range timeline {
|
||||
if e.Kind == events.KindChangesCaptured {
|
||||
captured = append(captured, e)
|
||||
}
|
||||
}
|
||||
if len(captured) != 2 {
|
||||
t.Fatalf("changes_captured events = %d, want the push capture and the one OpenPR takes (%d)", len(captured), stored.PRNumber)
|
||||
}
|
||||
for i, e := range captured {
|
||||
if e.Attempt != task.Attempt || task.Attempt == 0 {
|
||||
t.Errorf("capture %d attempt = %d, want the task's own attempt %d", i, e.Attempt, task.Attempt)
|
||||
}
|
||||
}
|
||||
if captured[0].Stage != "commit-push" {
|
||||
t.Errorf("capture stage = %q, want the capturing stage", captured[0].Stage)
|
||||
}
|
||||
data, err := json.Marshal(captured[0].Data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload struct {
|
||||
CapturedAfter string `json:"captured_after"`
|
||||
PRNumber int `json:"pr_number"`
|
||||
Files []struct {
|
||||
Path string `json:"path"`
|
||||
Status string `json:"status"`
|
||||
} `json:"files"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &payload); err != nil {
|
||||
t.Fatalf("decode capture: %v", err)
|
||||
}
|
||||
if payload.CapturedAfter != "commit-push" {
|
||||
t.Errorf("captured_after = %q, want commit-push", payload.CapturedAfter)
|
||||
}
|
||||
if payload.PRNumber != 0 {
|
||||
t.Errorf("the push capture carries pr_number %d, want 0: no PR existed when it was taken", payload.PRNumber)
|
||||
}
|
||||
if len(payload.Files) != 1 || payload.Files[0].Path != ".archie/bootstrap.md" || payload.Files[0].Status != "added" {
|
||||
t.Errorf("captured files = %+v, want the bootstrap marker as an added file", payload.Files)
|
||||
}
|
||||
|
||||
finalData, err := json.Marshal(captured[1].Data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var final struct {
|
||||
CapturedAfter string `json:"captured_after"`
|
||||
PRNumber int `json:"pr_number"`
|
||||
}
|
||||
if err := json.Unmarshal(finalData, &final); err != nil {
|
||||
t.Fatalf("decode the final capture: %v", err)
|
||||
}
|
||||
if final.CapturedAfter != "open-pr" || final.PRNumber != stored.PRNumber || final.PRNumber == 0 {
|
||||
t.Errorf("final capture = %q pr %d, want open-pr carrying the stored PR number %d, without which the changed-files view has nothing to link",
|
||||
final.CapturedAfter, final.PRNumber, stored.PRNumber)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTaskRestoresWorktreeOwnershipOnEveryExit pins the half of the
|
||||
// worktree-ownership contract that archie-core#520 left open. CommitAll and
|
||||
// Push hand the worktree back to the daemon's own UID on the SUCCESS path;
|
||||
// every other way a container run can end -- a gate failure that parks the
|
||||
// task, a stage error, an early return -- used to leave the worktree owned by
|
||||
// root, because the agent runs as root inside the container. The daemon then
|
||||
// could not clean or reset those paths on the next attempt (a root-owned
|
||||
// directory cannot be unlinked from by its non-root owner), so a retry failed
|
||||
// before it could start no matter what the worktree refresh did.
|
||||
//
|
||||
// The run below exits early, which is the point: the restore has to be
|
||||
// deferred over the whole run rather than attached to the paths that happen to
|
||||
// commit. It is observed through a supplementary group -- a non-root process
|
||||
// may move a file it owns into a group it is a member of, so this proves the
|
||||
// chown ran without needing root.
|
||||
func TestRunTaskRestoresWorktreeOwnershipOnEveryExit(t *testing.T) {
|
||||
probeGroup := supplementaryGroup(t)
|
||||
workDir := t.TempDir()
|
||||
probe := filepath.Join(workDir, "probe.txt")
|
||||
if err := os.WriteFile(probe, []byte("x\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Setenv("WORKTREE_UID", strconv.Itoa(os.Getuid()))
|
||||
t.Setenv("WORKTREE_GID", strconv.Itoa(probeGroup))
|
||||
|
||||
// A runner factory that yields nothing fails the run after the trees (and
|
||||
// the ownership defer) are already in place.
|
||||
_, err := runTask(t.Context(), taskrun.Request{
|
||||
Task: &workflow.Task{ID: 77, Branch: "feat/77-probe", Workflow: "implement"},
|
||||
Repo: config.Repo{Owner: "acme", Name: "widget", Base: "main"},
|
||||
}, taskDependencies{steps: testSteps(t)}, runnerFactory(func(map[string]agentexec.Provider, *slog.Logger) agentexec.Runner {
|
||||
return nil
|
||||
}), workDir, slog.New(slog.DiscardHandler))
|
||||
if err == nil {
|
||||
t.Fatal("runTask error = nil, want the missing-runner failure this exit is built around")
|
||||
}
|
||||
|
||||
info, statErr := os.Stat(probe)
|
||||
if statErr != nil {
|
||||
t.Fatal(statErr)
|
||||
}
|
||||
gid, ok := info.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
t.Fatal("no syscall.Stat_t for the ownership probe")
|
||||
}
|
||||
if int(gid.Gid) != probeGroup {
|
||||
t.Errorf("probe.txt gid = %d, want %d -- a run that never reached CommitAll or Push left the worktree owned by the container's own user", gid.Gid, probeGroup)
|
||||
}
|
||||
}
|
||||
|
||||
// supplementaryGroup returns a group this process is a member of but that is
|
||||
// not its primary gid, so a test can observe a chown a non-root process is
|
||||
// allowed to make.
|
||||
func supplementaryGroup(t *testing.T) int {
|
||||
t.Helper()
|
||||
groups, err := os.Getgroups()
|
||||
if err != nil {
|
||||
t.Skipf("os.Getgroups: %v", err)
|
||||
}
|
||||
for _, gid := range groups {
|
||||
if gid != os.Getgid() {
|
||||
return gid
|
||||
}
|
||||
}
|
||||
t.Skip("process belongs to no supplementary group to chown into")
|
||||
return 0
|
||||
}
|
||||
|
||||
// TestExecuteTaskRequestUsesInfrastructureRPCDependencies preserves the
|
||||
// application-to-infrastructure proof: the application asks Transport for its
|
||||
// forge/store/tree contracts, and those concrete clients cross embedded NATS
|
||||
// to daemon-side RPC servers before the bootstrap workflow can complete.
|
||||
func TestExecuteTaskRequestUsesInfrastructureRPCDependencies(t *testing.T) {
|
||||
if _, err := exec.LookPath("git"); err != nil {
|
||||
t.Skip("git not installed")
|
||||
}
|
||||
ctx := t.Context()
|
||||
host := newLocalRemote(t, "acme", "rpc-widget")
|
||||
st := pgstore.Open(t)
|
||||
if _, err := st.EnqueueIssue(ctx, "acme", "rpc-widget", 2, "feat: RPC bootstrap test", "", "bootstrap", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := st.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("claim = (%+v, %v)", task, err)
|
||||
}
|
||||
forge := &prCapturingForge{}
|
||||
daemonTrees := &worktree.Manager{
|
||||
WorkDir: t.TempDir(),
|
||||
Token: "unused-for-file-remotes",
|
||||
BotUser: "archie-bot",
|
||||
BotEmail: "archie-bot@example.com",
|
||||
BaseURL: "file://" + host,
|
||||
}
|
||||
hostDir, branch, err := daemonTrees.Prepare(ctx, "acme", "rpc-widget", "main", 2, task.Title, "", "bootstrap", worktree.Fresh)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task.Branch = branch
|
||||
grants := worktreerpc.NewGrants()
|
||||
grant, revokeGrant, err := grants.Issue(task)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(revokeGrant)
|
||||
|
||||
srv := startEmbeddedTaskRPCServer(t)
|
||||
serverConn := connectTaskRPC(t, srv.ClientURL())
|
||||
unsubForge, err := (&forgerpc.Server{Forge: forge, Log: slog.New(slog.DiscardHandler)}).Register(serverConn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(unsubForge)
|
||||
unsubTrees, err := (&worktreerpc.Server{Trees: daemonTrees, Grants: grants, Log: slog.New(slog.DiscardHandler)}).Register(serverConn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(unsubTrees)
|
||||
|
||||
transport, err := agentnats.Connect(ctx, agentnats.Config{URL: srv.ClientURL(), StateStoreURL: startStateStoreGRPC(t, st)}, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(transport.Close)
|
||||
|
||||
request := taskrun.Request{
|
||||
Task: task,
|
||||
Repo: config.Repo{Owner: "acme", Name: "rpc-widget", Base: "main"},
|
||||
Cfg: config.Config{}.ForTask(),
|
||||
WorktreeGrant: grant,
|
||||
}
|
||||
response, err := executeTaskRequest(ctx, request, transport, hostDir, slog.New(slog.DiscardHandler), testSteps(t), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Status != workflow.StatusPROpen || len(forge.prs) != 1 {
|
||||
t.Fatalf("response status/PRs = (%q, %d), want (%q, 1)", response.Status, len(forge.prs), workflow.StatusPROpen)
|
||||
}
|
||||
// archie-core-1786751948782-3-837a8fd0 point 4: every response reports
|
||||
// what this worker actually is, since it's the only channel the daemon
|
||||
// has to learn what's really running (see daemon.AgentStatus).
|
||||
if response.AgentVersion != Version() {
|
||||
t.Errorf("response.AgentVersion = %q, want Version() = %q", response.AgentVersion, Version())
|
||||
}
|
||||
if response.AgentInstallType != installtype.Type() {
|
||||
t.Errorf("response.AgentInstallType = %q, want installtype.Type() = %q", response.AgentInstallType, installtype.Type())
|
||||
}
|
||||
stored, err := st.TaskByIssue(ctx, "acme", "rpc-widget", 2)
|
||||
if err != nil || stored == nil || stored.Status != workflow.StatusPROpen || stored.PRNumber != 5 {
|
||||
t.Fatalf("stored task = (%+v, %v), want RPC-persisted PR-open task #5", stored, err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(hostDir, ".archie", "bootstrap.md")); err != nil {
|
||||
t.Fatalf("expected bootstrap marker file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExecuteTaskRequestForwardsWorkflowEventsOverNATS is the regression test
|
||||
// for the "No events yet" dashboard bug (archie-core-518): a workflow run
|
||||
// through the NATS/container path publishes its stage/outcome events to an
|
||||
// in-process *events.Bus nothing on the daemon side could see, because
|
||||
// runTask never wired TaskContext.Bus. This proves the fix end to end -- a
|
||||
// bystander subscribed directly to SubjectForEvents(task.ID) on the same
|
||||
// embedded NATS server executeTaskRequest uses receives real events the
|
||||
// bootstrap workflow emits, exactly as the daemon's own subscriber would.
|
||||
func TestExecuteTaskRequestForwardsWorkflowEventsOverNATS(t *testing.T) {
|
||||
if _, err := exec.LookPath("git"); err != nil {
|
||||
t.Skip("git not installed")
|
||||
}
|
||||
ctx := t.Context()
|
||||
host := newLocalRemote(t, "acme", "events-widget")
|
||||
st := pgstore.Open(t)
|
||||
if _, err := st.EnqueueIssue(ctx, "acme", "events-widget", 3, "feat: events bootstrap test", "", "bootstrap", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := st.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("claim = (%+v, %v)", task, err)
|
||||
}
|
||||
forge := &prCapturingForge{}
|
||||
daemonTrees := &worktree.Manager{
|
||||
WorkDir: t.TempDir(),
|
||||
Token: "unused-for-file-remotes",
|
||||
BotUser: "archie-bot",
|
||||
BotEmail: "archie-bot@example.com",
|
||||
BaseURL: "file://" + host,
|
||||
}
|
||||
hostDir, branch, err := daemonTrees.Prepare(ctx, "acme", "events-widget", "main", 3, task.Title, "", "bootstrap", worktree.Fresh)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task.Branch = branch
|
||||
grants := worktreerpc.NewGrants()
|
||||
grant, revokeGrant, err := grants.Issue(task)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(revokeGrant)
|
||||
|
||||
srv := startEmbeddedTaskRPCServer(t)
|
||||
serverConn := connectTaskRPC(t, srv.ClientURL())
|
||||
unsubForge, err := (&forgerpc.Server{Forge: forge, Log: slog.New(slog.DiscardHandler)}).Register(serverConn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(unsubForge)
|
||||
unsubTrees, err := (&worktreerpc.Server{Trees: daemonTrees, Grants: grants, Log: slog.New(slog.DiscardHandler)}).Register(serverConn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(unsubTrees)
|
||||
|
||||
// Stand in for the daemon's own SubjectEventsWildcard subscriber: bind
|
||||
// to the exact per-task subject before the workflow runs, so nothing
|
||||
// published during the run can be missed.
|
||||
var (
|
||||
mu sync.Mutex
|
||||
received []events.Event
|
||||
)
|
||||
bystander := connectTaskRPC(t, srv.ClientURL())
|
||||
eventSub, err := bystander.Subscribe(agentexec.SubjectForEvents(task.ID), func(msg *natsio.Msg) {
|
||||
var e events.Event
|
||||
if err := json.Unmarshal(msg.Data, &e); err != nil {
|
||||
t.Errorf("undecodable event message: %v", err)
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
received = append(received, e)
|
||||
mu.Unlock()
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = eventSub.Unsubscribe() })
|
||||
if err := bystander.Flush(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
transport, err := agentnats.Connect(ctx, agentnats.Config{URL: srv.ClientURL(), StateStoreURL: startStateStoreGRPC(t, st)}, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(transport.Close)
|
||||
|
||||
request := taskrun.Request{
|
||||
Task: task,
|
||||
Repo: config.Repo{Owner: "acme", Name: "events-widget", Base: "main"},
|
||||
Cfg: config.Config{}.ForTask(),
|
||||
WorktreeGrant: grant,
|
||||
}
|
||||
response, err := executeTaskRequest(ctx, request, transport, hostDir, slog.New(slog.DiscardHandler), testSteps(t), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Status != workflow.StatusPROpen {
|
||||
t.Fatalf("response status = %q, want %q", response.Status, workflow.StatusPROpen)
|
||||
}
|
||||
|
||||
deadline := time.After(2 * time.Second)
|
||||
for {
|
||||
mu.Lock()
|
||||
sawOutcome := false
|
||||
for _, e := range received {
|
||||
if e.Kind == events.KindOutcome {
|
||||
sawOutcome = true
|
||||
break
|
||||
}
|
||||
}
|
||||
mu.Unlock()
|
||||
if sawOutcome {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-deadline:
|
||||
t.Fatal("no \"outcome\" event arrived on SubjectForEvents(task.ID) within 2s")
|
||||
case <-time.After(10 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
sawOutcome := false
|
||||
for _, e := range received {
|
||||
if e.TaskID != task.ID {
|
||||
t.Errorf("event %+v carries TaskID %d, want %d", e, e.TaskID, task.ID)
|
||||
}
|
||||
if e.Kind == events.KindOutcome {
|
||||
sawOutcome = true
|
||||
}
|
||||
}
|
||||
if !sawOutcome {
|
||||
t.Errorf("received %d events %+v, want at least one %q", len(received), received, events.KindOutcome)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRouteTaskUsesRequestKindOverride is the regression for
|
||||
// workflow-engine-1: a kind -> workflow override loaded by the daemon is
|
||||
// carried in the taskrun request and applied by the worker process, so
|
||||
// workflow.Route honours it instead of silently falling back to the
|
||||
// built-in default (bug -> tdd).
|
||||
func TestRouteTaskUsesRequestKindOverride(t *testing.T) {
|
||||
t.Cleanup(func() {
|
||||
workflow.SetKindWorkflows(nil)
|
||||
workflow.SetLabelWorkflows(nil)
|
||||
})
|
||||
|
||||
registry := workflow.Registry{
|
||||
"tdd": workflow.Workflow{Name: "tdd"},
|
||||
"bootstrap": workflow.Workflow{Name: "bootstrap"},
|
||||
"implement": workflow.Workflow{Name: "implement"},
|
||||
}
|
||||
req := taskrun.Request{
|
||||
Task: &workflow.Task{Labels: "bug"},
|
||||
KindWorkflows: workflow.KindWorkflows{workintake.KindBug: "bootstrap"},
|
||||
}
|
||||
|
||||
wf := routeTask(req, registry)
|
||||
if wf.Name != "bootstrap" {
|
||||
t.Fatalf("routeTask() = %q, want %q (request kind override not applied)", wf.Name, "bootstrap")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRouteTaskUsesRequestLabelOverride is the label counterpart: an
|
||||
// arbitrary-label binding carried in the request also reaches the worker's
|
||||
// routing decision.
|
||||
func TestRouteTaskUsesRequestLabelOverride(t *testing.T) {
|
||||
t.Cleanup(func() {
|
||||
workflow.SetKindWorkflows(nil)
|
||||
workflow.SetLabelWorkflows(nil)
|
||||
})
|
||||
|
||||
registry := workflow.Registry{
|
||||
"implement": workflow.Workflow{Name: "implement"},
|
||||
"security-review": workflow.Workflow{Name: "security-review"},
|
||||
}
|
||||
req := taskrun.Request{
|
||||
Task: &workflow.Task{Labels: "security"},
|
||||
LabelWorkflows: workflow.LabelWorkflows{"security": "security-review"},
|
||||
}
|
||||
|
||||
wf := routeTask(req, registry)
|
||||
if wf.Name != "security-review" {
|
||||
t.Fatalf("routeTask() = %q, want %q (request label override not applied)", wf.Name, "security-review")
|
||||
}
|
||||
}
|
||||
|
||||
// changeStatsReader mirrors the unexported optional interface package workflow
|
||||
// type-asserts on TaskContext.Trees to capture what an attempt changed. It is
|
||||
// restated here because an unexported interface cannot be named from this
|
||||
// package; the assertion below is therefore the only way this side can pin
|
||||
// that the in-container Trees is capable at all.
|
||||
type changeStatsReader interface {
|
||||
ChangedFileStats(ctx context.Context, dir, base string) (task.ChangeStats, error)
|
||||
}
|
||||
|
||||
// TestHybridTreesCanReportWhatChanged is the in-container half of the change
|
||||
// capture. Every production workflow.Run executes in archie-agent against a
|
||||
// hybridTrees, so a Trees without this capability would make the capture a
|
||||
// silent no-op in exactly the deployment that produces all the real data --
|
||||
// the daemon-side manager being capable would prove nothing.
|
||||
func TestHybridTreesCanReportWhatChanged(t *testing.T) {
|
||||
var trees any = &hybridTrees{local: &worktree.Manager{}}
|
||||
if _, ok := trees.(changeStatsReader); !ok {
|
||||
t.Fatal("hybridTrees cannot report a diffstat; every capture inside a container would silently no-op")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHybridTreesForwardsChangedFileStatsToItsLocalManager drives the
|
||||
// capability against a real worktree, so satisfaction of the interface is not
|
||||
// mistaken for a working forwarder.
|
||||
func TestHybridTreesForwardsChangedFileStatsToItsLocalManager(t *testing.T) {
|
||||
if _, err := exec.LookPath("git"); err != nil {
|
||||
t.Skip("git not installed")
|
||||
}
|
||||
ctx := t.Context()
|
||||
host := newLocalRemote(t, "acme", "diffstat")
|
||||
manager := &worktree.Manager{
|
||||
WorkDir: t.TempDir(), Token: "unused",
|
||||
BotUser: "archie-bot", BotEmail: "archie-bot@example.com", BaseURL: "file://" + host,
|
||||
}
|
||||
dir, branch, err := manager.Prepare(ctx, "acme", "diffstat", "main", 4, "feat: widget", "", "", worktree.Fresh)
|
||||
if err != nil {
|
||||
t.Fatalf("prepare: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "widget.txt"), []byte("one\ntwo\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := manager.CommitAll(ctx, dir, "feat: widget"); err != nil {
|
||||
t.Fatalf("commit: %v", err)
|
||||
}
|
||||
|
||||
trees := &hybridTrees{local: manager, localDir: dir, branch: branch}
|
||||
stats, err := trees.ChangedFileStats(ctx, dir, "main")
|
||||
if err != nil {
|
||||
t.Fatalf("ChangedFileStats: %v", err)
|
||||
}
|
||||
if len(stats.Files) != 1 || stats.Files[0].Path != "widget.txt" {
|
||||
t.Fatalf("files = %+v, want the one committed file", stats.Files)
|
||||
}
|
||||
if stats.Totals != (task.ChangeTotals{Files: 1, Additions: 2}) {
|
||||
t.Errorf("totals = %+v, want the file's two added lines", stats.Totals)
|
||||
}
|
||||
if stats.HeadSHA == "" || stats.BaseSHA == "" {
|
||||
t.Errorf("SHAs = (%q, %q), want both resolved", stats.BaseSHA, stats.HeadSHA)
|
||||
}
|
||||
}
|
||||
|
||||
// uncommittedChangeReporter mirrors the unexported optional interface package
|
||||
// workflow type-asserts on TaskContext.Trees to tell a change that is not
|
||||
// committed yet from a branch with no change. It is restated here for the same
|
||||
// reason changeStatsReader is: an unexported interface cannot be named from this
|
||||
// package, so this assertion is the only way this side can pin that the
|
||||
// in-container Trees can answer at all.
|
||||
type uncommittedChangeReporter interface {
|
||||
HasUncommittedChanges(ctx context.Context, dir string) (bool, error)
|
||||
}
|
||||
|
||||
// TestHybridTreesCanReportUncommittedWork is the in-container half of the
|
||||
// diff-rules placement guard. Every production workflow.Run executes in
|
||||
// archie-agent against a hybridTrees, and a workflow whose only Trees cannot
|
||||
// answer would fail the guard for the wrong reason -- or, worse, look capable
|
||||
// while forwarding nothing.
|
||||
func TestHybridTreesCanReportUncommittedWork(t *testing.T) {
|
||||
var trees any = &hybridTrees{local: &worktree.Manager{}}
|
||||
if _, ok := trees.(uncommittedChangeReporter); !ok {
|
||||
t.Fatal("hybridTrees cannot report uncommitted work, so the in-container diff-rules guard would refuse every run")
|
||||
}
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
package agentworker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
agentnats "github.com/samcharles93/archie-core/internal/infrastructure/agenttransport/nats"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
)
|
||||
|
||||
// stubRunner is the agent runner that lets a test workflow end in an
|
||||
// agent.run tail without an LLM: the call step under test needs no agent,
|
||||
// but the workflow must still end with an outcome.
|
||||
type stubRunner struct{}
|
||||
|
||||
func (stubRunner) Run(_ context.Context, _ string, req agentexec.Request, _ agentexec.ToolCallReporter) (agentexec.Result, error) {
|
||||
return agentexec.Result{
|
||||
Version: agentexec.ProtocolVersion, TaskID: req.TaskID, Attempt: req.Attempt,
|
||||
Stage: req.Stage, Status: agentexec.StatusPassed, Summary: "reported",
|
||||
}, nil
|
||||
}
|
||||
|
||||
// fakeScratchTrees is the Trees for a scratch task: the workspace already
|
||||
// exists (the call step needs none, the agent.run tail works in it), and
|
||||
// nothing publishes.
|
||||
type fakeScratchTrees struct {
|
||||
dir string
|
||||
}
|
||||
|
||||
func (f *fakeScratchTrees) Prepare(context.Context, string, string, string, int, string, string, string, workflow.PrepareTarget) (string, string, error) {
|
||||
return f.dir, "", nil
|
||||
}
|
||||
|
||||
func (*fakeScratchTrees) CommitAll(context.Context, string, string) (bool, error) { return false, nil }
|
||||
func (*fakeScratchTrees) Push(context.Context) error { return nil }
|
||||
func (*fakeScratchTrees) Diff(context.Context, string, string) (string, error) { return "", nil }
|
||||
func (*fakeScratchTrees) ChangedFiles(context.Context, string, string) ([]string, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (*fakeScratchTrees) ChangedLines(context.Context, string, string) (int, error) { return 0, nil }
|
||||
func (*fakeScratchTrees) Snapshot(context.Context, string, string) error { return nil }
|
||||
|
||||
// TestExecuteTaskRequestStartsWorkflowCallCallee proves the engine's
|
||||
// task.Caller wiring end to end: a run of a repository-none workflow carrying
|
||||
// one workflow.call step starts a real callee task row through the same
|
||||
// State Store gRPC contract the production worker dials
|
||||
// (docs/prds/workflow-calls.md), and the caller carries on to its tail.
|
||||
func TestExecuteTaskRequestStartsWorkflowCallCallee(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
st := pgstore.Open(t)
|
||||
|
||||
const callerYAML = "id: caller\nrepository: none\ninputs:\n src_ip: {type: string}\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n inputs: {src_ip: \"inputs.src_ip\"}\n wait: false\n - type: agent.run\n settings:\n mission: report\n"
|
||||
// A real caller row, claimed and running, so the store's enqueue reads
|
||||
// the same row shape production does.
|
||||
task, err := st.EnqueueChatTask(ctx, "", "", "workflow.call integration", "", "caller", "", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("seed caller task: %v", err)
|
||||
}
|
||||
if err := st.Transition(ctx, task.ID, task.Status, workflow.StatusRunning, "started"); err != nil {
|
||||
t.Fatalf("claim caller: %v", err)
|
||||
}
|
||||
task.Status = workflow.StatusRunning
|
||||
task.Inputs = map[string]any{"src_ip": "10.0.0.9"}
|
||||
task.WorkflowDefinitionYAML = callerYAML
|
||||
task.WorkflowDefinitionDigest = workflow.DigestDefinition(callerYAML)
|
||||
if err := st.Update(ctx, task); err != nil {
|
||||
t.Fatalf("seed caller task: %v", err)
|
||||
}
|
||||
|
||||
natsSrv := startEmbeddedTaskRPCServer(t)
|
||||
transport, err := agentnats.Connect(ctx, agentnats.Config{
|
||||
URL: natsSrv.ClientURL(),
|
||||
StateStoreURL: startStateStoreGRPC(t, st),
|
||||
}, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(transport.Close)
|
||||
|
||||
workDir := t.TempDir()
|
||||
request := taskrun.Request{
|
||||
Task: task,
|
||||
Repo: config.Repo{},
|
||||
Cfg: config.Config{Models: map[string]string{"builder": "p/m"}}.ForTask(),
|
||||
WorkflowDefinition: callerYAML,
|
||||
}
|
||||
dependencies := taskDependencies{
|
||||
store: transport.Store(rpcTimeout),
|
||||
calls: transport.Calls(rpcTimeout),
|
||||
trees: &fakeScratchTrees{dir: workDir},
|
||||
steps: testSteps(t),
|
||||
}
|
||||
fakeRunner := runnerFactory(func(map[string]agentexec.Provider, *slog.Logger) agentexec.Runner { return stubRunner{} })
|
||||
response, err := runTask(ctx, request, dependencies, fakeRunner, workDir, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Status != workflow.StatusCompleted {
|
||||
t.Fatalf("response status = %q (park reason %q), want completed", response.Status, response.Task.ParkReason)
|
||||
}
|
||||
|
||||
callee := calleeTaskOf(t, ctx, st, task.ID)
|
||||
if callee.Workflow != "callee" || callee.CallParentTaskID != task.ID || callee.CallDepth != 1 {
|
||||
t.Fatalf("callee = %+v, want workflow callee linked to task %d at depth 1", callee, task.ID)
|
||||
}
|
||||
if callee.Inputs["src_ip"] != "10.0.0.9" {
|
||||
t.Fatalf("callee inputs = %+v, want the call's resolved reference", callee.Inputs)
|
||||
}
|
||||
if callee.Org != org.OrgID("default") {
|
||||
t.Fatalf("callee org = %q, want the caller's %q", callee.Org, task.Org)
|
||||
}
|
||||
}
|
||||
|
||||
// calleeTaskOf reads the one callee task whose call_parent_task_id is
|
||||
// callerTaskID, straight off the pool the test owns.
|
||||
func calleeTaskOf(t *testing.T, ctx context.Context, st *pgstore.TaskDB, callerTaskID int64) *workflow.Task {
|
||||
t.Helper()
|
||||
rows, err := st.Pool.Query(ctx,
|
||||
`SELECT id, workflow, call_parent_task_id, call_depth, org_id, inputs
|
||||
FROM tasks WHERE call_parent_task_id = $1`, callerTaskID)
|
||||
if err != nil {
|
||||
t.Fatalf("callee query: %v", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var callees []*workflow.Task
|
||||
for rows.Next() {
|
||||
var id, parent, depth int64
|
||||
var wf, orgID, inputs string
|
||||
if err := rows.Scan(&id, &wf, &parent, &depth, &orgID, &inputs); err != nil {
|
||||
t.Fatalf("callee scan: %v", err)
|
||||
}
|
||||
decoded, _ := workflowtask.DecodeInputs(inputs)
|
||||
callees = append(callees, &workflow.Task{
|
||||
ID: id, Workflow: wf, CallParentTaskID: parent, CallDepth: int(depth),
|
||||
Org: org.OrgID(orgID), Inputs: decoded,
|
||||
})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
t.Fatalf("callee rows: %v", err)
|
||||
}
|
||||
if len(callees) != 1 {
|
||||
t.Fatalf("callee tasks of %d = %+v, want exactly one", callerTaskID, callees)
|
||||
}
|
||||
return callees[0]
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package agentworker
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestVersionReportsDevWhenUnstamped guards the unstamped-build fallback:
|
||||
// an empty ldflags value (e.g. a local `go build`, or a release pipeline
|
||||
// that forgot -X for this package) must read as "dev", the same
|
||||
// placeholder cmd/archied's own version vars use, not as an empty string
|
||||
// that would silently sail through daemon.AgentStatus as a real version.
|
||||
func TestVersionReportsDevWhenUnstamped(t *testing.T) {
|
||||
orig := version
|
||||
t.Cleanup(func() { version = orig })
|
||||
version = ""
|
||||
|
||||
if got := Version(); got != "dev" {
|
||||
t.Errorf("Version() = %q, want %q", got, "dev")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVersionReportsStampedValue(t *testing.T) {
|
||||
orig := version
|
||||
t.Cleanup(func() { version = orig })
|
||||
version = "1.9.11"
|
||||
|
||||
if got := Version(); got != "1.9.11" {
|
||||
t.Errorf("Version() = %q, want %q", got, "1.9.11")
|
||||
}
|
||||
}
|
||||
@@ -1,233 +0,0 @@
|
||||
package agentworker
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
agentnats "github.com/samcharles93/archie-core/internal/infrastructure/agenttransport/nats"
|
||||
)
|
||||
|
||||
type workerPublisher struct{ messages *[][]byte }
|
||||
|
||||
func (p workerPublisher) Publish(_ string, data []byte) error {
|
||||
if p.messages != nil {
|
||||
*p.messages = append(*p.messages, append([]byte(nil), data...))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type workerSubscription struct {
|
||||
close func()
|
||||
closeErr error
|
||||
}
|
||||
|
||||
func (s workerSubscription) Close() error {
|
||||
s.close()
|
||||
return s.closeErr
|
||||
}
|
||||
|
||||
type workerTransportStub struct {
|
||||
events *[]string
|
||||
subscribeErr error
|
||||
subCloseErr error
|
||||
publisher agentexec.LogPublisher
|
||||
eventPublisher agentexec.EventPublisher
|
||||
taskID int64
|
||||
}
|
||||
|
||||
func (t *workerTransportStub) Close() { *t.events = append(*t.events, "transport-close") }
|
||||
func (t *workerTransportStub) LogPublisher() agentexec.LogPublisher {
|
||||
*t.events = append(*t.events, "log-publisher")
|
||||
if t.publisher != nil {
|
||||
return t.publisher
|
||||
}
|
||||
return workerPublisher{}
|
||||
}
|
||||
|
||||
func (t *workerTransportStub) EventPublisher() agentexec.EventPublisher {
|
||||
*t.events = append(*t.events, "event-publisher")
|
||||
if t.eventPublisher != nil {
|
||||
return t.eventPublisher
|
||||
}
|
||||
return workerPublisher{}
|
||||
}
|
||||
|
||||
func (t *workerTransportStub) SubscribeTasks(_ context.Context, taskID int64, _ agentnats.TaskHandler, _ *slog.Logger) (agentnats.Subscription, error) {
|
||||
*t.events = append(*t.events, "subscribe")
|
||||
t.taskID = taskID
|
||||
if t.subscribeErr != nil {
|
||||
return nil, t.subscribeErr
|
||||
}
|
||||
return workerSubscription{
|
||||
close: func() { *t.events = append(*t.events, "subscription-close") },
|
||||
closeErr: t.subCloseErr,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (*workerTransportStub) Forger(string, time.Duration) workflow.Forger { return nil }
|
||||
|
||||
func (*workerTransportStub) Store(time.Duration) workflow.Store { return nil }
|
||||
|
||||
func (*workerTransportStub) Calls(time.Duration) task.Caller { return nil }
|
||||
|
||||
func (*workerTransportStub) Trees(string, string, time.Duration) agentnats.RemoteTrees { return nil }
|
||||
|
||||
func TestRunPassesCompleteTransportConfiguration(t *testing.T) {
|
||||
var got agentnats.Config
|
||||
var events []string
|
||||
transport := &workerTransportStub{events: &events}
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
dependencies := workerDependencies{
|
||||
markSafe: func(context.Context, string, *slog.Logger) bool { return true },
|
||||
connect: func(_ context.Context, config agentnats.Config, _ *slog.Logger) (workerTransport, error) {
|
||||
got = config
|
||||
return transport, nil
|
||||
},
|
||||
bootID: func(string) (int64, error) { return 42, nil },
|
||||
wait: func(context.Context, *slog.Logger) { cancel() },
|
||||
}
|
||||
settings := Settings{NATSURL: "nats://test", NATSToken: "secret", WorkDir: "/worktree"}
|
||||
if err := run(ctx, settings, slog.New(slog.DiscardHandler), dependencies); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.URL != settings.NATSURL || got.Token != settings.NATSToken {
|
||||
t.Fatalf("connection config = %#v, want URL/token from settings", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunPreservesStartupAndReverseCleanupOrder(t *testing.T) {
|
||||
var events []string
|
||||
transport := &workerTransportStub{events: &events}
|
||||
dependencies := workerDependencies{
|
||||
markSafe: func(context.Context, string, *slog.Logger) bool {
|
||||
events = append(events, "git-safety")
|
||||
return true
|
||||
},
|
||||
connect: func(context.Context, agentnats.Config, *slog.Logger) (workerTransport, error) {
|
||||
events = append(events, "connect")
|
||||
return transport, nil
|
||||
},
|
||||
bootID: func(string) (int64, error) {
|
||||
events = append(events, "boot-id")
|
||||
return 42, nil
|
||||
},
|
||||
wait: func(context.Context, *slog.Logger) {
|
||||
events = append(events, "wait")
|
||||
},
|
||||
}
|
||||
if err := run(t.Context(), Settings{NATSURL: "nats://test", WorkDir: "/worktree"}, slog.New(slog.DiscardHandler), dependencies); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{"git-safety", "connect", "boot-id", "log-publisher", "subscribe", "wait", "subscription-close", "transport-close"}
|
||||
if len(events) != len(want) {
|
||||
t.Fatalf("events = %v, want %v", events, want)
|
||||
}
|
||||
for i := range want {
|
||||
if events[i] != want[i] {
|
||||
t.Fatalf("events = %v, want %v", events, want)
|
||||
}
|
||||
}
|
||||
if transport.taskID != 42 {
|
||||
t.Fatalf("subscription task ID = %d, want 42", transport.taskID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunWarnsWhenNormalSubscriptionCleanupFails(t *testing.T) {
|
||||
closeErr := errors.New("unsubscribe failed")
|
||||
var events []string
|
||||
transport := &workerTransportStub{events: &events, subCloseErr: closeErr}
|
||||
dependencies := workerDependencies{
|
||||
markSafe: func(context.Context, string, *slog.Logger) bool { return true },
|
||||
connect: func(context.Context, agentnats.Config, *slog.Logger) (workerTransport, error) {
|
||||
return transport, nil
|
||||
},
|
||||
bootID: func(string) (int64, error) { return 42, nil },
|
||||
wait: func(context.Context, *slog.Logger) {},
|
||||
}
|
||||
var output bytes.Buffer
|
||||
if err := run(t.Context(), Settings{NATSURL: "nats://test"}, slog.New(slog.NewTextHandler(&output, nil)), dependencies); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(output.String(), "task run unsubscribe failed") || !strings.Contains(output.String(), closeErr.Error()) {
|
||||
t.Fatalf("cleanup log = %q, want warning containing %q", output.String(), closeErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunStartupFailuresCleanUpOwnedResources(t *testing.T) {
|
||||
connectErr := errors.New("connect failed")
|
||||
bootErr := errors.New("invalid boot metadata")
|
||||
subscribeErr := errors.New("subscribe failed")
|
||||
tests := []struct {
|
||||
name string
|
||||
connectErr error
|
||||
bootErr error
|
||||
subscribeErr error
|
||||
wantErr error
|
||||
wantOperation string
|
||||
wantClosed bool
|
||||
}{
|
||||
{name: "connect", connectErr: connectErr, wantErr: connectErr, wantOperation: "nats connect failed"},
|
||||
{name: "boot metadata", bootErr: bootErr, wantErr: bootErr, wantOperation: "task boot failed", wantClosed: true},
|
||||
{name: "subscribe", subscribeErr: subscribeErr, wantErr: subscribeErr, wantOperation: "taskrun subscribe failed", wantClosed: true},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var events []string
|
||||
var published [][]byte
|
||||
transport := &workerTransportStub{events: &events, subscribeErr: test.subscribeErr, publisher: workerPublisher{messages: &published}}
|
||||
dependencies := workerDependencies{
|
||||
markSafe: func(context.Context, string, *slog.Logger) bool { return true },
|
||||
connect: func(context.Context, agentnats.Config, *slog.Logger) (workerTransport, error) {
|
||||
return transport, test.connectErr
|
||||
},
|
||||
bootID: func(string) (int64, error) {
|
||||
if test.bootErr != nil {
|
||||
return 0, test.bootErr
|
||||
}
|
||||
return 42, nil
|
||||
},
|
||||
wait: func(context.Context, *slog.Logger) { t.Fatal("wait called") },
|
||||
}
|
||||
var output bytes.Buffer
|
||||
err := run(t.Context(), Settings{NATSURL: "nats://test"}, slog.New(slog.NewTextHandler(&output, nil)), dependencies)
|
||||
if !errors.Is(err, test.wantErr) {
|
||||
t.Fatalf("error = %v, want %v", err, test.wantErr)
|
||||
}
|
||||
var startupErr *StartupError
|
||||
if !errors.As(err, &startupErr) || startupErr.Operation != test.wantOperation {
|
||||
t.Fatalf("startup error = %#v, want operation %q", startupErr, test.wantOperation)
|
||||
}
|
||||
closed := len(events) > 0 && events[len(events)-1] == "transport-close"
|
||||
if closed != test.wantClosed {
|
||||
t.Fatalf("transport closed = %v, want %v; events %v", closed, test.wantClosed, events)
|
||||
}
|
||||
if test.bootErr != nil {
|
||||
for _, event := range events {
|
||||
if event == "subscribe" {
|
||||
t.Fatalf("invalid boot metadata reached task subscription: events %v", events)
|
||||
}
|
||||
}
|
||||
}
|
||||
if got := strings.Count(output.String(), test.wantOperation); got != 1 {
|
||||
t.Fatalf("operation log count = %d, want 1; output %q", got, output.String())
|
||||
}
|
||||
if test.subscribeErr != nil {
|
||||
var joined strings.Builder
|
||||
for _, data := range published {
|
||||
joined.WriteString(string(data))
|
||||
}
|
||||
if !strings.Contains(joined.String(), test.wantOperation) {
|
||||
t.Fatalf("task-scoped logs %q do not contain %q", joined.String(), test.wantOperation)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIsAccessResetArgs(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
want bool
|
||||
}{
|
||||
{name: "org reset", args: []string{"access", "reset", "--org", "acme"}, want: true},
|
||||
{name: "instance reset", args: []string{"access", "reset", "--instance"}, want: true},
|
||||
{name: "config first", args: []string{"access", "reset", "-config", "/tmp/config.toml", "--org", "acme"}, want: true},
|
||||
{name: "setup is not a reset", args: []string{"setup"}, want: false},
|
||||
{name: "bare access", args: []string{"access"}, want: false},
|
||||
{name: "other subcommand", args: []string{"access", "grant"}, want: false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := IsAccessResetArgs(tt.args); got != tt.want {
|
||||
t.Fatalf("IsAccessResetArgs(%v) = %v, want %v", tt.args, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunAccessResetUsage(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
wantCode int
|
||||
wantText string
|
||||
}{
|
||||
{name: "no target", args: nil, wantCode: 2, wantText: "exactly one of --org"},
|
||||
{name: "both targets", args: []string{"--org", "acme", "--instance"}, wantCode: 2, wantText: "exactly one of --org"},
|
||||
{name: "unexpected argument", args: []string{"--instance", "extra"}, wantCode: 2, wantText: "unexpected argument"},
|
||||
{name: "unknown flag", args: []string{"--workspace", "net"}, wantCode: 2},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var stderr strings.Builder
|
||||
code := RunAccessReset(t.Context(), tt.args, &stderr)
|
||||
if code != tt.wantCode {
|
||||
t.Fatalf("RunAccessReset(%v) = %d, want %d (stderr: %s)", tt.args, code, tt.wantCode, stderr.String())
|
||||
}
|
||||
if tt.wantText != "" && !strings.Contains(stderr.String(), tt.wantText) {
|
||||
t.Fatalf("stderr = %q, want it to name %q", stderr.String(), tt.wantText)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/moby/moby/client"
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/container"
|
||||
)
|
||||
|
||||
// setupContainers must discover the bridge before embedded NATS starts, but
|
||||
// its cleanup registration comes afterwards. boot.cleanup is LIFO, so this
|
||||
// ordering stops worker containers before closing the daemon client and the
|
||||
// embedded server they are connected to.
|
||||
func TestSetupBackendsRegistersContainerCleanupAfterNATS(t *testing.T) {
|
||||
fileset := token.NewFileSet()
|
||||
file, err := parser.ParseFile(fileset, "bootstrap.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
setupContainers := methodBody(t, file, "setupContainers")
|
||||
if methodCallPosition(setupContainers, "addCleanup") != token.NoPos {
|
||||
t.Fatal("setupContainers registers cleanup before NATS; LIFO would stop the broker before workers")
|
||||
}
|
||||
setupBackends := methodBody(t, file, "setupBackends")
|
||||
connect := methodCallPosition(setupBackends, "connectNATS")
|
||||
register := methodCallPosition(setupBackends, "addCleanup")
|
||||
if connect == token.NoPos || register == token.NoPos || register < connect {
|
||||
t.Fatalf("setupBackends call positions: connectNATS=%d addCleanup=%d, want container cleanup registered after connect", connect, register)
|
||||
}
|
||||
}
|
||||
|
||||
// methodBody returns the body of the func or method named name. It matches on
|
||||
// name alone, so a package-level function (such as Run in main.go) resolves as
|
||||
// well as a method; names are unique per package.
|
||||
func methodBody(t *testing.T, file *ast.File, name string) *ast.BlockStmt {
|
||||
t.Helper()
|
||||
for _, decl := range file.Decls {
|
||||
fn, ok := decl.(*ast.FuncDecl)
|
||||
if ok && fn.Name.Name == name {
|
||||
return fn.Body
|
||||
}
|
||||
}
|
||||
t.Fatalf("method %s not found", name)
|
||||
return nil
|
||||
}
|
||||
|
||||
func methodCallPosition(body *ast.BlockStmt, name string) token.Pos {
|
||||
position := token.NoPos
|
||||
ast.Inspect(body, func(node ast.Node) bool {
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
selector, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if ok && selector.Sel.Name == name && position == token.NoPos {
|
||||
position = call.Pos()
|
||||
}
|
||||
return true
|
||||
})
|
||||
return position
|
||||
}
|
||||
|
||||
// This is the native-daemon deployment seam: Docker supplies the host-side
|
||||
// gateway of the worker bridge, embedded NATS binds that address, and the
|
||||
// runtime credential shared with workers is required by the same listener.
|
||||
func TestConnectEmbeddedNATSUsesManagedWorkerBridge(t *testing.T) {
|
||||
const gateway = "127.0.0.1"
|
||||
dockerAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/networks/workers"):
|
||||
writeDockerResponse(t, w, map[string]any{
|
||||
"Name": "workers",
|
||||
"Driver": "bridge",
|
||||
"Scope": "local",
|
||||
"IPAM": map[string]any{
|
||||
"Config": []map[string]string{{
|
||||
"Subnet": "127.0.0.0/8",
|
||||
"Gateway": gateway,
|
||||
}},
|
||||
},
|
||||
})
|
||||
case strings.HasSuffix(r.URL.Path, "/containers/json"):
|
||||
writeDockerResponse(t, w, []any{})
|
||||
default:
|
||||
http.Error(w, fmt.Sprintf("unexpected Docker API path %s", r.URL.Path), http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(dockerAPI.Close)
|
||||
|
||||
dockerClient, err := client.New(client.WithHost(dockerAPI.URL), client.WithAPIVersion("1.55"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = dockerClient.Close() })
|
||||
|
||||
pool, err := container.NewPool(t.Context(), container.Config{
|
||||
DockerClient: dockerClient,
|
||||
Network: "workers",
|
||||
RequireHostGateway: true,
|
||||
}, nil, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatalf("container.NewPool = %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = pool.Close() })
|
||||
|
||||
b := &boot{
|
||||
cfg: config.Config{
|
||||
StateDir: t.TempDir(),
|
||||
NATS: config.NATSConfig{Mode: config.NATSModeEmbedded},
|
||||
},
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
containerPool: pool,
|
||||
}
|
||||
if err := b.connectNATS(t.Context()); err != nil {
|
||||
t.Fatalf("connectNATS = %v", err)
|
||||
}
|
||||
t.Cleanup(b.cleanup)
|
||||
|
||||
if !strings.HasPrefix(b.natsURL, "nats://"+gateway+":") {
|
||||
t.Errorf("connected NATS URL = %q, want bridge gateway %s", b.natsURL, gateway)
|
||||
}
|
||||
if b.natsToken == "" {
|
||||
t.Fatal("connected NATS token is empty")
|
||||
}
|
||||
if unauthenticated, connectErr := natsio.Connect(b.natsURL); connectErr == nil {
|
||||
unauthenticated.Close()
|
||||
t.Fatal("unauthenticated worker connection succeeded")
|
||||
}
|
||||
authenticated, err := natsio.Connect(b.natsURL, natsio.Token(b.natsToken))
|
||||
if err != nil {
|
||||
t.Fatalf("authenticated worker connection = %v", err)
|
||||
}
|
||||
authenticated.Close()
|
||||
}
|
||||
|
||||
func writeDockerResponse(t *testing.T, w http.ResponseWriter, value any) {
|
||||
t.Helper()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if err := json.NewEncoder(w).Encode(value); err != nil {
|
||||
t.Errorf("encode Docker response: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectExternalNATSEmptyURLReturnsConfigurationError(t *testing.T) {
|
||||
b := newBootstrap()
|
||||
b.cfg.NATS = config.NATSConfig{Mode: config.NATSModeExternal}
|
||||
|
||||
err := b.connectNATS(t.Context())
|
||||
if err == nil || !strings.Contains(err.Error(), "nats.url is required") {
|
||||
t.Fatalf("connectNATS() error = %v, want useful missing-url error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupObservabilityDoesNotTouchDaemonBeforeBuild(t *testing.T) {
|
||||
fileset := token.NewFileSet()
|
||||
file, err := parser.ParseFile(fileset, "bootstrap.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
setup := methodBody(t, file, "setupObservability")
|
||||
var daemonAssignments int
|
||||
ast.Inspect(setup, func(node ast.Node) bool {
|
||||
assign, ok := node.(*ast.AssignStmt)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
for _, lhs := range assign.Lhs {
|
||||
if selector, ok := lhs.(*ast.SelectorExpr); ok {
|
||||
if receiver, ok := selector.X.(*ast.SelectorExpr); ok && receiver.Sel.Name == "d" {
|
||||
daemonAssignments++
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
if daemonAssignments != 0 {
|
||||
t.Fatalf("setupObservability assigns daemon fields %d times; daemon is built later", daemonAssignments)
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
func TestChatRepoEnvSingleIdentity(t *testing.T) {
|
||||
cfg := config.Config{
|
||||
Forge: config.Forge{Host: "https://github.com", Type: "github"},
|
||||
Repos: []config.Repo{
|
||||
{Owner: "my-org", Name: "frontend-app", Base: "develop"},
|
||||
{Owner: "my-org", Name: "backend-api"},
|
||||
},
|
||||
}
|
||||
got := chatRepoEnv(cfg, "")
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("expected 2 repos, got %d", len(got))
|
||||
}
|
||||
if got[0].FullName != "my-org/frontend-app" || got[0].Forge != "https://github.com" || got[0].DefaultBranch != "develop" {
|
||||
t.Errorf("repo 0 mismatch: %+v", got[0])
|
||||
}
|
||||
// Base empty -> the daemon's effective default branch (main), not a guess.
|
||||
if got[1].DefaultBranch != "main" {
|
||||
t.Errorf("expected default branch main, got %q", got[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatRepoEnvMultiIdentityMatchesActive(t *testing.T) {
|
||||
cfg := config.Config{
|
||||
Identities: []config.IdentityConfig{
|
||||
{Name: "alpha", Forge: config.Forge{Host: "https://gitea.example.com"}, Repos: []config.Repo{{Owner: "alpha", Name: "app"}}},
|
||||
{Name: "beta", Forge: config.Forge{Host: "https://github.com"}, Repos: []config.Repo{{Owner: "beta", Name: "svc"}}},
|
||||
},
|
||||
}
|
||||
got := chatRepoEnv(cfg, "beta")
|
||||
if len(got) != 1 || got[0].FullName != "beta/svc" || got[0].Forge != "https://github.com" {
|
||||
t.Fatalf("expected the active identity's scope, got %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatRepoEnvMultiIdentityFallsBackToFirstWithRepos(t *testing.T) {
|
||||
cfg := config.Config{
|
||||
Identities: []config.IdentityConfig{
|
||||
{Name: "a", Forge: config.Forge{}, Repos: nil},
|
||||
{Name: "b", Forge: config.Forge{Host: "https://github.com"}, Repos: []config.Repo{{Owner: "b", Name: "svc"}}},
|
||||
},
|
||||
}
|
||||
got := chatRepoEnv(cfg, "no-such-identity")
|
||||
if len(got) != 1 || got[0].FullName != "b/svc" {
|
||||
t.Fatalf("expected fallback to the first identity with repos, got %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatRepoEnvPreservesEmptyForge(t *testing.T) {
|
||||
cfg := config.Config{
|
||||
Repos: []config.Repo{{Owner: "acme", Name: "widgets"}},
|
||||
}
|
||||
got := chatRepoEnv(cfg, "")
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("expected 1 repo, got %d", len(got))
|
||||
}
|
||||
if got[0].Forge != "" {
|
||||
t.Errorf("expected empty forge to be preserved (so the prompt renders 'forge unknown'), got %q", got[0].Forge)
|
||||
}
|
||||
if got[0].DefaultBranch != "main" {
|
||||
t.Errorf("expected default branch main, got %q", got[0].DefaultBranch)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatRepoEnvEmpty(t *testing.T) {
|
||||
if got := chatRepoEnv(config.Config{}, ""); len(got) != 0 {
|
||||
t.Fatalf("expected no repos, got %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// TestWebhookUserIdentityNeverReturnsTheRoutePath guards
|
||||
// docs/prds/memory-engine-unification.md §3 and §4's specific webhook
|
||||
// requirement: internal/channels/webhook/webhook.go carries the configured route
|
||||
// path in Inbound.BudgetKey, never in SenderID, and no platform may turn one into
|
||||
// a user identity however plausible it looks as one.
|
||||
func TestWebhookUserIdentityNeverReturnsTheRoutePath(t *testing.T) {
|
||||
resolver := userIdentityResolver()
|
||||
id, ok := resolver(messaging.Inbound{
|
||||
Platform: "webhook",
|
||||
Message: messaging.Message{SenderID: "/github", Sender: "webhook"},
|
||||
})
|
||||
if ok || id != "" {
|
||||
t.Fatalf("webhook resolver = (%q, %v), want (\"\", false)", id, ok)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUserIdentityResolverPerPlatform documents the composition's per-platform
|
||||
// choice: telegram and email carry a native sender id, the dashboard ("web") and
|
||||
// webhook do not, and a platform nobody has decided about fails closed.
|
||||
//
|
||||
// It is keyed on the message's platform rather than a resolver per channel,
|
||||
// because one Gateway Router serves every channel: closing over a channel name
|
||||
// resolved every turn as "web" (archie-core-c1qx).
|
||||
func TestUserIdentityResolverPerPlatform(t *testing.T) {
|
||||
tests := []struct {
|
||||
platform string
|
||||
senderID string
|
||||
wantOK bool
|
||||
}{
|
||||
{"telegram", "12345", true},
|
||||
{"email", "person@example.com", true},
|
||||
{"web", "anything", false},
|
||||
{"webhook", "/github", false},
|
||||
{"unknown-future-channel", "anything", false},
|
||||
{"", "anything", false},
|
||||
}
|
||||
resolver := userIdentityResolver()
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.platform, func(t *testing.T) {
|
||||
id, ok := resolver(messaging.Inbound{Platform: tt.platform, Message: messaging.Message{SenderID: tt.senderID}})
|
||||
if ok != tt.wantOK {
|
||||
t.Fatalf("%s resolver ok = %v, want %v", tt.platform, ok, tt.wantOK)
|
||||
}
|
||||
if ok && string(id) != tt.senderID {
|
||||
t.Fatalf("%s resolver id = %q, want %q", tt.platform, id, tt.senderID)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestUserIdentityResolverFailsClosedOnEmptySenderID guards §3's "fail closed":
|
||||
// an empty SenderID (a channel that carries no per-caller id for this particular
|
||||
// message) must resolve to no identity, never an empty-string identity that
|
||||
// Subject would treat as present.
|
||||
func TestUserIdentityResolverFailsClosedOnEmptySenderID(t *testing.T) {
|
||||
resolver := userIdentityResolver()
|
||||
id, ok := resolver(messaging.Inbound{Platform: "telegram", Message: messaging.Message{SenderID: ""}})
|
||||
if ok || id != "" {
|
||||
t.Fatalf("telegram resolver with no sender id = (%q, %v), want (\"\", false)", id, ok)
|
||||
}
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestChatModelManagerBuildsUniqueCatalogAndSelectsChatDefault(t *testing.T) {
|
||||
manager := newChatModelManager(map[string]string{
|
||||
"builder": "provider/zeta",
|
||||
"chat": "provider/alpha",
|
||||
"review": "provider/zeta",
|
||||
"empty": "",
|
||||
})
|
||||
|
||||
models := manager.Models()
|
||||
if len(models) != 2 || models[0] != "provider/alpha" || models[1] != "provider/zeta" {
|
||||
t.Fatalf("Models() = %v, want sorted unique model references", models)
|
||||
}
|
||||
models[0] = "mutated"
|
||||
if got := manager.Models()[0]; got != "provider/alpha" {
|
||||
t.Fatalf("Models() exposed internal state: first model = %q", got)
|
||||
}
|
||||
if got := manager.ActiveModel(); got != "provider/alpha" {
|
||||
t.Fatalf("ActiveModel() = %q, want chat model", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatModelManagerFallsBackToBuilder(t *testing.T) {
|
||||
manager := newChatModelManager(map[string]string{
|
||||
"builder": "provider/builder",
|
||||
"review": "provider/reviewer",
|
||||
})
|
||||
|
||||
if got := manager.ActiveModel(); got != "provider/builder" {
|
||||
t.Fatalf("ActiveModel() = %q, want builder fallback", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatModelManagerSwitchesOnlyToConfiguredModels(t *testing.T) {
|
||||
manager := newChatModelManager(map[string]string{
|
||||
"chat": "provider/one",
|
||||
"review": "provider/two",
|
||||
})
|
||||
|
||||
if err := manager.SetActiveModel(context.Background(), "provider/two"); err != nil {
|
||||
t.Fatalf("SetActiveModel() error = %v", err)
|
||||
}
|
||||
if got := manager.ActiveModel(); got != "provider/two" {
|
||||
t.Fatalf("ActiveModel() = %q, want switched model", got)
|
||||
}
|
||||
|
||||
if err := manager.SetActiveModel(context.Background(), "provider/unknown"); err == nil {
|
||||
t.Fatal("SetActiveModel() error = nil, want unknown-model error")
|
||||
}
|
||||
if got := manager.ActiveModel(); got != "provider/two" {
|
||||
t.Fatalf("failed switch changed ActiveModel() to %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatModelManagerHonorsCancelledContext(t *testing.T) {
|
||||
manager := newChatModelManager(map[string]string{
|
||||
"chat": "provider/one",
|
||||
"review": "provider/two",
|
||||
})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
if err := manager.SetActiveModel(ctx, "provider/two"); err == nil {
|
||||
t.Fatal("SetActiveModel() error = nil, want context cancellation")
|
||||
}
|
||||
if got := manager.ActiveModel(); got != "provider/one" {
|
||||
t.Fatalf("cancelled switch changed ActiveModel() to %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatModelManagerSeparatesProvidersAndModels(t *testing.T) {
|
||||
manager := newChatModelManager(map[string]string{
|
||||
"chat": "openrouter/openai/gpt-5.6",
|
||||
"builder": "openai/gpt-5.6",
|
||||
"review": "anthropic/claude-opus",
|
||||
})
|
||||
|
||||
providers := manager.Providers()
|
||||
if len(providers) != 3 ||
|
||||
providers[0] != "anthropic" ||
|
||||
providers[1] != "openai" ||
|
||||
providers[2] != "openrouter" {
|
||||
t.Fatalf("Providers() = %v", providers)
|
||||
}
|
||||
if got := manager.ActiveProvider(); got != "openrouter" {
|
||||
t.Fatalf("ActiveProvider() = %q, want openrouter", got)
|
||||
}
|
||||
if got := manager.ModelsForProvider("openai"); len(got) != 1 || got[0] != "openai/gpt-5.6" {
|
||||
t.Fatalf("openai models = %v", got)
|
||||
}
|
||||
if got := manager.ModelsForProvider("openrouter"); len(got) != 1 || got[0] != "openrouter/openai/gpt-5.6" {
|
||||
t.Fatalf("openrouter models = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatModelManagerProviderSwitchSelectsValidModel(t *testing.T) {
|
||||
manager := newChatModelManager(map[string]string{
|
||||
"chat": "openrouter/openai/gpt-5.6",
|
||||
"builder": "openai/gpt-5.6",
|
||||
"review": "openai/o3",
|
||||
})
|
||||
|
||||
if err := manager.SetActiveProvider(context.Background(), "openai"); err != nil {
|
||||
t.Fatalf("SetActiveProvider() error = %v", err)
|
||||
}
|
||||
if got := manager.ActiveProvider(); got != "openai" {
|
||||
t.Fatalf("ActiveProvider() = %q, want openai", got)
|
||||
}
|
||||
if got := manager.ActiveModel(); got != "openai/gpt-5.6" {
|
||||
t.Fatalf("ActiveModel() = %q, want first configured openai model", got)
|
||||
}
|
||||
|
||||
if err := manager.SetActiveProvider(context.Background(), "missing"); err == nil {
|
||||
t.Fatal("SetActiveProvider() error = nil, want unknown-provider error")
|
||||
}
|
||||
if got := manager.ActiveProvider(); got != "openai" {
|
||||
t.Fatalf("failed switch changed provider to %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatModelManagerIncludesExplicitChatCatalog(t *testing.T) {
|
||||
manager := newChatModelManager(
|
||||
map[string]string{"chat": "openai/gpt-5.6-sol"},
|
||||
[]string{
|
||||
"openrouter/openai/gpt-5.6-sol",
|
||||
"anthropic/claude-opus",
|
||||
"openai/gpt-5.6-sol",
|
||||
},
|
||||
)
|
||||
|
||||
if got := manager.Models(); len(got) != 3 {
|
||||
t.Fatalf("Models() = %v, want workflow model plus explicit catalog", got)
|
||||
}
|
||||
if got := manager.ModelsForProvider("openrouter"); len(got) != 1 ||
|
||||
got[0] != "openrouter/openai/gpt-5.6-sol" {
|
||||
t.Fatalf("OpenRouter catalog = %v", got)
|
||||
}
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
func TestComposeChatContractRejectsInvalidSettings(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
settings config.Services
|
||||
}{
|
||||
{name: "missing target", settings: config.Services{}},
|
||||
{name: "blank target", settings: config.Services{config.ServiceNameGateway: {Target: " \t\n"}}},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
chat, cleanup, err := composeChatContract(tt.settings, &secret.Registry{})
|
||||
if cleanup != nil {
|
||||
t.Cleanup(cleanup)
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatal("invalid settings were accepted")
|
||||
}
|
||||
if chat != nil || cleanup != nil {
|
||||
t.Fatal("invalid settings published an adapter or cleanup")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestComposeChatContractNonLoopbackFailsClosed(t *testing.T) {
|
||||
_, _, err := composeChatContract(
|
||||
config.Services{config.ServiceNameGateway: {Target: "gateway.example.com:8585"}},
|
||||
&secret.Registry{},
|
||||
)
|
||||
if err == nil {
|
||||
t.Fatal("non-loopback target without a token should fail closed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestComposeChatContractRemoteAndCleanup(t *testing.T) {
|
||||
listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
server := grpc.NewServer()
|
||||
gatewayrpc.RegisterServer(server, compositionChat{snapshot: gateway.ChatSnapshot{ActiveModel: "remote-model"}})
|
||||
serveDone := make(chan error, 1)
|
||||
go func() { serveDone <- server.Serve(listener) }()
|
||||
t.Cleanup(func() {
|
||||
server.Stop()
|
||||
_ = listener.Close()
|
||||
if err := <-serveDone; err != nil {
|
||||
t.Errorf("serve chat: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
chat, cleanup, err := composeChatContract(
|
||||
config.Services{config.ServiceNameGateway: {Target: listener.Addr().String()}},
|
||||
&secret.Registry{},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cleanup == nil {
|
||||
t.Fatal("remote composition returned no cleanup")
|
||||
}
|
||||
t.Cleanup(cleanup)
|
||||
if _, ok := chat.(*gatewayrpc.Client); !ok {
|
||||
t.Fatalf("remote composition returned %T", chat)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
snapshot, err := chat.Snapshot(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if snapshot.ActiveModel != "remote-model" {
|
||||
t.Fatalf("Snapshot used wrong adapter: ActiveModel = %q", snapshot.ActiveModel)
|
||||
}
|
||||
cleanup()
|
||||
if _, err := chat.Snapshot(ctx); status.Code(err) != codes.Canceled {
|
||||
t.Fatalf("Snapshot after cleanup: code = %v, want Canceled; error = %v", status.Code(err), err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGatewayResolvedToken pins the daemon-side wiring rather than the
|
||||
// precedence rule itself: config.Services.ResolvedToken owns the rule and is
|
||||
// tested there, but only this level proves the gateway reads it through the
|
||||
// secret registry and lands on the env var its registration names.
|
||||
func TestGatewayResolvedToken(t *testing.T) {
|
||||
secrets := &secret.Registry{}
|
||||
explicit := config.Services{config.ServiceNameGateway: {TargetToken: "file-token"}}
|
||||
if got := explicit.ResolvedToken(config.ServiceNameGateway, secrets.Getenv); got != "file-token" {
|
||||
t.Fatalf("resolved token = %q, want file-token", got)
|
||||
}
|
||||
t.Setenv("GATEWAY_TOKEN", "environment-token")
|
||||
empty := config.Services{config.ServiceNameGateway: {}}
|
||||
if got := empty.ResolvedToken(config.ServiceNameGateway, secrets.Getenv); got != "environment-token" {
|
||||
t.Fatalf("resolved token = %q, want environment-token", got)
|
||||
}
|
||||
if got := explicit.ResolvedToken(config.ServiceNameGateway, secrets.Getenv); got != "file-token" {
|
||||
t.Fatalf("explicit target_token should win over the environment, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
type compositionChat struct {
|
||||
gateway.ChatContract
|
||||
snapshot gateway.ChatSnapshot
|
||||
}
|
||||
|
||||
func (c compositionChat) Snapshot(context.Context) (gateway.ChatSnapshot, error) {
|
||||
return c.snapshot, nil
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/daemon"
|
||||
"github.com/samcharles93/archie-core/internal/installtype"
|
||||
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
||||
)
|
||||
|
||||
// TestMakeUpdateServiceWiresInstallType is the regression test for
|
||||
// archie-core-522's fail-closed guarantee actually reaching production: a
|
||||
// Service built without InstallType always refuses to install (see
|
||||
// releaseupdate.ErrUnknownInstallType), so wiring it here is what makes
|
||||
// /update work at all for a correctly-stamped build, not just a detail.
|
||||
func TestMakeUpdateServiceWiresInstallType(t *testing.T) {
|
||||
cfg := config.Config{}
|
||||
cfg.Chat.Telegram.UpdateCheckCommand = []string{"archie-update-check"}
|
||||
cfg.Chat.Telegram.UpdateInstallCommand = []string{"archie-update-install"}
|
||||
|
||||
service := makeUpdateService(chatSetup{Cfg: config.NewHolder(cfg)})
|
||||
|
||||
if service == nil {
|
||||
t.Fatal("makeUpdateService returned nil despite a configured check command")
|
||||
}
|
||||
if service.InstallType != installtype.Type() {
|
||||
t.Errorf("Service.InstallType = %q, want installtype.Type() = %q", service.InstallType, installtype.Type())
|
||||
}
|
||||
if service.Enrich == nil {
|
||||
t.Fatal("Service.Enrich is nil; component InstallType/Reference will never be populated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestComponentInstallTypeEnricherDaemon(t *testing.T) {
|
||||
enrich := componentInstallTypeEnricher(nil, config.NATSConfig{})
|
||||
|
||||
gotType, gotRef := enrich(releaseupdate.ComponentDaemon)
|
||||
if gotType != installtype.Type() || gotRef != "" {
|
||||
t.Errorf("daemon = (%q, %q), want (%q, \"\")", gotType, gotRef, installtype.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestComponentInstallTypeEnricherAgentBeforeAnyObservation(t *testing.T) {
|
||||
var status daemon.AgentStatus
|
||||
enrich := componentInstallTypeEnricher(&status, config.NATSConfig{})
|
||||
|
||||
gotType, gotRef := enrich(releaseupdate.ComponentAgent)
|
||||
if gotType != "" || gotRef != "" {
|
||||
t.Errorf("agent before any Observe = (%q, %q), want (\"\", \"\")", gotType, gotRef)
|
||||
}
|
||||
}
|
||||
|
||||
func TestComponentInstallTypeEnricherAgentAfterObservation(t *testing.T) {
|
||||
var status daemon.AgentStatus
|
||||
status.Observe("1.9.11", "container")
|
||||
enrich := componentInstallTypeEnricher(&status, config.NATSConfig{})
|
||||
|
||||
gotType, _ := enrich(releaseupdate.ComponentAgent)
|
||||
if gotType != "container" {
|
||||
t.Errorf("agent InstallType = %q, want the observed install type %q", gotType, "container")
|
||||
}
|
||||
}
|
||||
|
||||
func TestComponentInstallTypeEnricherAgentNilStatus(t *testing.T) {
|
||||
enrich := componentInstallTypeEnricher(nil, config.NATSConfig{})
|
||||
|
||||
gotType, gotRef := enrich(releaseupdate.ComponentAgent)
|
||||
if gotType != "" || gotRef != "" {
|
||||
t.Errorf("agent with nil AgentStatus = (%q, %q), want (\"\", \"\")", gotType, gotRef)
|
||||
}
|
||||
}
|
||||
|
||||
func TestComponentInstallTypeEnricherNATS(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
nats config.NATSConfig
|
||||
wantType string
|
||||
wantRef string
|
||||
}{
|
||||
{name: "embedded", nats: config.NATSConfig{Mode: "embedded"}, wantType: "embedded", wantRef: ""},
|
||||
{name: "external", nats: config.NATSConfig{Mode: "external", URL: "nats://nats.internal:4222"}, wantType: "external", wantRef: "nats://nats.internal:4222"},
|
||||
{name: "off", nats: config.NATSConfig{Mode: "off"}, wantType: "", wantRef: ""},
|
||||
{name: "unset", nats: config.NATSConfig{}, wantType: "", wantRef: ""},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
enrich := componentInstallTypeEnricher(nil, test.nats)
|
||||
gotType, gotRef := enrich(releaseupdate.ComponentNATS)
|
||||
if gotType != test.wantType || gotRef != test.wantRef {
|
||||
t.Errorf("nats(%+v) = (%q, %q), want (%q, %q)", test.nats, gotType, gotRef, test.wantType, test.wantRef)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestComponentInstallTypeEnricherUnknownComponent(t *testing.T) {
|
||||
enrich := componentInstallTypeEnricher(nil, config.NATSConfig{})
|
||||
|
||||
gotType, gotRef := enrich("something-else")
|
||||
if gotType != "" || gotRef != "" {
|
||||
t.Errorf("unknown component = (%q, %q), want (\"\", \"\")", gotType, gotRef)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDaemonRunningVersionsVouchesOnlyForItselfWithoutAgentStatus: the point
|
||||
// of checking a pending update report against running versions is that the
|
||||
// value checked against is ground truth. This process's own compiled-in
|
||||
// version is; a guess at the agent's is not, because runtimeVersion records
|
||||
// what archied's release pipeline stamped, not what an agent container is
|
||||
// actually running. Before any task has reported an observed agent version
|
||||
// (agentStatus nil, or nothing observed yet), including one would recreate
|
||||
// the false success the check exists to catch, so its absence is the
|
||||
// assertion.
|
||||
func TestDaemonRunningVersionsVouchesOnlyForItselfWithoutAgentStatus(t *testing.T) {
|
||||
running := daemonRunningVersions(nil)
|
||||
|
||||
if got := running[releaseupdate.ComponentDaemon]; got != gatewayVersion {
|
||||
t.Errorf("running[%q] = %q, want gatewayVersion = %q", releaseupdate.ComponentDaemon, got, gatewayVersion)
|
||||
}
|
||||
if _, ok := running[releaseupdate.ComponentAgent]; ok {
|
||||
t.Errorf("running vouches for %q, which this process cannot verify: %#v",
|
||||
releaseupdate.ComponentAgent, running)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDaemonRunningVersionsIncludesObservedAgent: once a task response has
|
||||
// actually self-reported an agent version (daemon.AgentStatus.Observe), that
|
||||
// -- not archied's release pipeline's expectation -- is ground truth for
|
||||
// what is running, so it belongs in the verification set.
|
||||
func TestDaemonRunningVersionsIncludesObservedAgent(t *testing.T) {
|
||||
var status daemon.AgentStatus
|
||||
status.Observe("1.9.11", "container")
|
||||
|
||||
running := daemonRunningVersions(&status)
|
||||
|
||||
if got := running[releaseupdate.ComponentAgent]; got != "1.9.11" {
|
||||
t.Errorf("running[%q] = %q, want the observed version %q", releaseupdate.ComponentAgent, got, "1.9.11")
|
||||
}
|
||||
}
|
||||
|
||||
// TestMakeUpdateServiceProbesTheDaemonsOwnHealthAddress: the watchdog is
|
||||
// verifying archied's restart, so it has to probe archied. The dashboard's
|
||||
// listener is the wrong answer twice over -- it can be switched off, and in
|
||||
// Phase 3 it belongs to another process, which would report health for
|
||||
// something the watchdog never restarted (archie-core-1r4g).
|
||||
func TestMakeUpdateServiceProbesTheDaemonsOwnHealthAddress(t *testing.T) {
|
||||
for _, tc := range []struct{ name, listen, want string }{
|
||||
{name: "default loopback", listen: "127.0.0.1:8485", want: "http://127.0.0.1:8485"},
|
||||
{name: "wildcard bind", listen: "0.0.0.0:8485", want: "http://localhost:8485"},
|
||||
{name: "operator-chosen port", listen: "127.0.0.1:9500", want: "http://127.0.0.1:9500"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cfg := config.Config{}
|
||||
cfg.Health.Listen = tc.listen
|
||||
// The dashboard's own address must not leak into the probe.
|
||||
cfg.Web.Listen = "127.0.0.1:8484"
|
||||
cfg.Chat.Telegram.UpdateCheckCommand = []string{"archie-update-check"}
|
||||
cfg.Chat.Telegram.UpdateInstallCommand = []string{"archie-update-install"}
|
||||
|
||||
service := makeUpdateService(chatSetup{Cfg: config.NewHolder(cfg)})
|
||||
|
||||
if service == nil {
|
||||
t.Fatal("makeUpdateService returned nil despite a configured check command")
|
||||
}
|
||||
installer, ok := service.Installer.(releaseupdate.CommandInstaller)
|
||||
if !ok {
|
||||
t.Fatalf("Service.Installer = %T, want releaseupdate.CommandInstaller", service.Installer)
|
||||
}
|
||||
if installer.HealthURL != tc.want {
|
||||
t.Errorf("Installer.HealthURL = %q, want %q", installer.HealthURL, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestRemoteChatCompositionPreservesChannelTurnLedger(t *testing.T) {
|
||||
cfg := config.Config{
|
||||
DatabaseURL: pgtest.URL(t),
|
||||
Services: config.Services{config.ServiceNameGateway: {Target: "127.0.0.1:1"}},
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
b := &boot{cfg: cfg, log: slog.Default(), cfgHolder: config.NewHolder(cfg), stateStore: st, personas: gateway.NewPersonaRegistry(gateway.DefaultPersonas())}
|
||||
t.Cleanup(b.cleanup)
|
||||
if err := b.openStores(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b.chatSessionStore == nil {
|
||||
t.Fatal("startup did not open the channel conversation store")
|
||||
}
|
||||
sessions := b.chatSessionStore
|
||||
if err := b.setupLLMAndChat(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b.chatSessionStore != sessions {
|
||||
t.Fatal("remote web chat replaced the channel conversation store")
|
||||
}
|
||||
ledger, ok := b.chatSessionStore.(gateway.TurnLedger)
|
||||
if !ok {
|
||||
t.Fatal("channel conversation store does not implement TurnLedger")
|
||||
}
|
||||
if err := ledger.RecoverTurns(t.Context(), "test-owner"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -1,273 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/core"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
// recordingStream captures the turn's reported progress in arrival order.
|
||||
type recordingStream struct {
|
||||
events []string
|
||||
}
|
||||
|
||||
func (s *recordingStream) Delta(text string) {
|
||||
s.events = append(s.events, "text:"+text)
|
||||
}
|
||||
|
||||
func (s *recordingStream) ToolCall(event gateway.ToolCallEvent) {
|
||||
s.events = append(s.events, "tool:"+event.Name+":"+event.Parameters+":"+event.Summary())
|
||||
}
|
||||
|
||||
func (s *recordingStream) Media(event gateway.MediaEvent) {
|
||||
// Path is recorded alongside the type: a local attachment that lost
|
||||
// its path on the way through would still look like a media event.
|
||||
s.events = append(s.events, "media:"+event.ToolName+":"+event.Attachment.Type+":"+event.Attachment.Path)
|
||||
}
|
||||
|
||||
func streamOf(parts ...core.StreamPart) <-chan core.StreamPart {
|
||||
ch := make(chan core.StreamPart, len(parts))
|
||||
for _, part := range parts {
|
||||
ch <- part
|
||||
}
|
||||
close(ch)
|
||||
return ch
|
||||
}
|
||||
|
||||
func TestDrainChatStream(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
parts []core.StreamPart
|
||||
wantText string
|
||||
wantEvents []string
|
||||
}{
|
||||
{
|
||||
name: "text only",
|
||||
parts: []core.StreamPart{
|
||||
{Type: core.StreamPartTextDelta, TextDelta: "hello "},
|
||||
{Type: core.StreamPartTextDelta, TextDelta: "world"},
|
||||
},
|
||||
wantText: "hello world",
|
||||
wantEvents: []string{"text:hello ", "text:world"},
|
||||
},
|
||||
{
|
||||
name: "a tool result is reported between the text around it",
|
||||
parts: []core.StreamPart{
|
||||
{Type: core.StreamPartTextDelta, TextDelta: "checking"},
|
||||
{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{ToolCallID: "1", ToolName: "shell", Input: `{"cmd":"true"}`}},
|
||||
{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{ToolCallID: "1", ToolName: "shell", Output: "exit 0"}},
|
||||
{Type: core.StreamPartTextDelta, TextDelta: " done"},
|
||||
},
|
||||
wantText: "checking done",
|
||||
wantEvents: []string{"text:checking", `tool:shell:{"cmd":"[string]"}:exit 0`, "text: done"},
|
||||
},
|
||||
{
|
||||
name: "a failed tool is reported as a failure, not silence",
|
||||
parts: []core.StreamPart{
|
||||
{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{ToolName: "shell", Error: "exit status 2"}},
|
||||
},
|
||||
wantEvents: []string{"tool:shell::failed: exit status 2"},
|
||||
},
|
||||
{
|
||||
// The tool call part carries no outcome yet: reporting it as
|
||||
// well would show every tool twice.
|
||||
name: "the tool call part alone reports nothing",
|
||||
parts: []core.StreamPart{
|
||||
{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{ToolName: "shell"}},
|
||||
},
|
||||
wantEvents: nil,
|
||||
},
|
||||
{
|
||||
name: "parts with nothing to render are skipped",
|
||||
parts: []core.StreamPart{
|
||||
{Type: core.StreamPartStartStep},
|
||||
{Type: core.StreamPartTextDelta, TextDelta: ""},
|
||||
{Type: core.StreamPartReasoningDelta, ReasoningDelta: "thinking"},
|
||||
{Type: core.StreamPartToolResult},
|
||||
{Type: core.StreamPartFinishStep},
|
||||
{Type: core.StreamPartFinish},
|
||||
},
|
||||
wantEvents: nil,
|
||||
},
|
||||
{
|
||||
// A tool's output carrying a tools.MultimodalResult envelope
|
||||
// must report both the ordinary tool-call event (so the turn
|
||||
// narrates what ran) and a Media event per URL, so the
|
||||
// channel has something to actually deliver.
|
||||
name: "a tool result carrying MultimodalResult URLs reports Media",
|
||||
parts: []core.StreamPart{
|
||||
{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{ToolCallID: "1", ToolName: "generate_video"}},
|
||||
{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{
|
||||
ToolCallID: "1",
|
||||
ToolName: "generate_video",
|
||||
Output: `{"is_multimodal":true,"urls":[{"type":"video","url":"https://x/v"}]}`,
|
||||
}},
|
||||
},
|
||||
wantEvents: []string{
|
||||
`tool:generate_video::{"is_multimodal":true,"urls":[{"type":"video","url":"https://x/v"}]}`,
|
||||
"media:generate_video:video:",
|
||||
},
|
||||
},
|
||||
{
|
||||
// A local file has no URL and must not acquire one: the
|
||||
// channel uploads it. Losing Path here is exactly the
|
||||
// silent non-delivery send_file exists to end.
|
||||
name: "a tool result carrying a local path reports Media with that path",
|
||||
parts: []core.StreamPart{
|
||||
{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{ToolCallID: "1", ToolName: "send_file"}},
|
||||
{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{
|
||||
ToolCallID: "1",
|
||||
ToolName: "send_file",
|
||||
Output: `{"is_multimodal":true,"urls":[{"type":"document","path":"/tmp/a.md"}]}`,
|
||||
}},
|
||||
},
|
||||
wantEvents: []string{
|
||||
"tool:send_file::" + `{"is_multimodal":true,"urls":[{"type":"document","path":"/tmp/a.md"}]}`,
|
||||
"media:send_file:document:/tmp/a.md",
|
||||
},
|
||||
},
|
||||
{
|
||||
// A ref naming neither a URL nor a path is not deliverable,
|
||||
// and an empty attachment would render as a delivered file.
|
||||
name: "a media ref with no source reports no Media event",
|
||||
parts: []core.StreamPart{
|
||||
{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{ToolCallID: "1", ToolName: "odd_tool"}},
|
||||
{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{
|
||||
ToolCallID: "1",
|
||||
ToolName: "odd_tool",
|
||||
Output: `{"is_multimodal":true,"urls":[{"type":"document"}]}`,
|
||||
}},
|
||||
},
|
||||
wantEvents: []string{"tool:odd_tool::" + `{"is_multimodal":true,"urls":[{"type":"document"}]}`},
|
||||
},
|
||||
{
|
||||
// An ordinary JSON tool result that happens to be a JSON
|
||||
// object but isn't a MultimodalResult (no is_multimodal, or
|
||||
// false) must not be misread as carrying media.
|
||||
name: "a plain JSON tool result reports no Media event",
|
||||
parts: []core.StreamPart{
|
||||
{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{ToolCallID: "1", ToolName: "read_file"}},
|
||||
{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{
|
||||
ToolCallID: "1",
|
||||
ToolName: "read_file",
|
||||
Output: `{"path":"a.txt","content":"hello"}`,
|
||||
}},
|
||||
},
|
||||
wantEvents: []string{`tool:read_file::{"path":"a.txt","content":"hello"}`},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
sink := &recordingStream{}
|
||||
text := drainChatStream(streamOf(tc.parts...), sink, nil)
|
||||
|
||||
if text != tc.wantText {
|
||||
t.Fatalf("text = %q, want %q", text, tc.wantText)
|
||||
}
|
||||
if len(sink.events) != len(tc.wantEvents) {
|
||||
t.Fatalf("events = %v, want %v", sink.events, tc.wantEvents)
|
||||
}
|
||||
for i := range tc.wantEvents {
|
||||
if sink.events[i] != tc.wantEvents[i] {
|
||||
t.Fatalf("events = %v, want %v", sink.events, tc.wantEvents)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDrainChatStreamCorrelatesBoundsAndRedactsToolParameters(t *testing.T) {
|
||||
secret := strings.Repeat("s", 200)
|
||||
sink := &recordingStream{}
|
||||
drainChatStream(streamOf(
|
||||
core.StreamPart{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{
|
||||
ToolCallID: "call-2",
|
||||
ToolName: "shell",
|
||||
Input: `{"cmd":"curl -H 'Authorization: Bearer ` + secret + `'","nested":{"api_token":"` + secret + `"}}`,
|
||||
}},
|
||||
core.StreamPart{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{
|
||||
ToolCallID: "call-1",
|
||||
ToolName: "read",
|
||||
Input: `{"path":"/tmp/one"}`,
|
||||
}},
|
||||
core.StreamPart{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{
|
||||
ToolCallID: "call-1",
|
||||
ToolName: "read",
|
||||
Output: "one",
|
||||
}},
|
||||
core.StreamPart{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{
|
||||
ToolCallID: "call-2",
|
||||
ToolName: "shell",
|
||||
Output: "ok",
|
||||
}},
|
||||
), sink, nil)
|
||||
|
||||
if len(sink.events) != 2 {
|
||||
t.Fatalf("events = %v, want two completed calls", sink.events)
|
||||
}
|
||||
if sink.events[0] != `tool:read:{"path":"[string]"}:one` {
|
||||
t.Fatalf("first event = %q, want parameters correlated by call ID", sink.events[0])
|
||||
}
|
||||
if strings.Contains(sink.events[1], secret) {
|
||||
t.Fatalf("second event exposed secret parameters: %q", sink.events[1])
|
||||
}
|
||||
if !strings.Contains(sink.events[1], `"api_token":"[redacted]"`) {
|
||||
t.Fatalf("second event = %q, want redacted token", sink.events[1])
|
||||
}
|
||||
if len([]rune(sink.events[1])) > 180 {
|
||||
t.Fatalf("second event is %d runes, want bounded parameters", len([]rune(sink.events[1])))
|
||||
}
|
||||
}
|
||||
|
||||
// The stream must be drained to close even when nobody is rendering it:
|
||||
// ai-sdk writes to FullStream synchronously, so an abandoned stream stalls
|
||||
// the generating goroutine.
|
||||
func TestDrainChatStreamWithoutASinkStillCollectsText(t *testing.T) {
|
||||
text := drainChatStream(streamOf(
|
||||
core.StreamPart{Type: core.StreamPartTextDelta, TextDelta: "a"},
|
||||
core.StreamPart{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{ToolName: "shell", Output: "ok"}},
|
||||
core.StreamPart{Type: core.StreamPartTextDelta, TextDelta: "b"},
|
||||
), nil, nil)
|
||||
|
||||
if text != "ab" {
|
||||
t.Fatalf("text = %q, want %q", text, "ab")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDrainChatStreamCarriesTheToolsRegisteredIcon pins the seam between the
|
||||
// tool registry and what a chat surface renders. The icon is looked up by
|
||||
// tool name at report time, so a tool that registers one gets it and a tool
|
||||
// that does not is reported without one rather than with a generic stand-in.
|
||||
func TestDrainChatStreamCarriesTheToolsRegisteredIcon(t *testing.T) {
|
||||
sink := &iconRecordingStream{}
|
||||
drainChatStream(streamOf(
|
||||
core.StreamPart{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{ToolName: "shell", Output: "ok"}},
|
||||
core.StreamPart{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{ToolName: "mcp.github.search", Output: "ok"}},
|
||||
), sink, map[string]string{"shell": "💻"})
|
||||
|
||||
want := []string{"shell:💻", "mcp.github.search:"}
|
||||
if len(sink.icons) != len(want) {
|
||||
t.Fatalf("icons = %v, want %v", sink.icons, want)
|
||||
}
|
||||
for i, w := range want {
|
||||
if sink.icons[i] != w {
|
||||
t.Errorf("icons[%d] = %q, want %q", i, sink.icons[i], w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type iconRecordingStream struct {
|
||||
icons []string
|
||||
}
|
||||
|
||||
func (s *iconRecordingStream) Delta(string) {}
|
||||
|
||||
func (s *iconRecordingStream) ToolCall(event gateway.ToolCallEvent) {
|
||||
s.icons = append(s.icons, event.Name+":"+event.Emoji)
|
||||
}
|
||||
|
||||
func (s *iconRecordingStream) Media(gateway.MediaEvent) {}
|
||||
@@ -1,116 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/chat"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
// TestBuildTurnMessagesAttachesMediaPartsToTheFinalUserMessage: inbound
|
||||
// media only reaches the model when the turn's request is turned into
|
||||
// message parts; the attachment belongs on the message the user just sent.
|
||||
func TestBuildTurnMessagesAttachesMediaPartsToTheFinalUserMessage(t *testing.T) {
|
||||
request := gateway.TurnModelRequest{
|
||||
Messages: []gateway.CompressedMessage{
|
||||
{Role: "system", Content: "sys"},
|
||||
{Role: "user", Content: "what is this?"},
|
||||
},
|
||||
Media: []gateway.MediaAttachment{
|
||||
{Type: "image", MIMEType: "image/png", Data: []byte("png-bytes")},
|
||||
{Type: "image", URL: "https://example.invalid/pic.jpg"},
|
||||
{Type: "document", MIMEType: "application/pdf", FileName: "report.pdf", Data: []byte("pdf-bytes")},
|
||||
},
|
||||
}
|
||||
|
||||
messages := buildTurnMessages(request)
|
||||
if len(messages) != 2 {
|
||||
t.Fatalf("messages = %d, want 2", len(messages))
|
||||
}
|
||||
if messages[0].Content != "sys" || len(messages[0].Parts) != 0 {
|
||||
t.Errorf("system message = %#v, want plain content and no parts", messages[0])
|
||||
}
|
||||
if messages[1].Content != "" {
|
||||
t.Errorf("user content = %q, want it moved into a text part", messages[1].Content)
|
||||
}
|
||||
parts := messages[1].Parts
|
||||
if len(parts) != 4 {
|
||||
t.Fatalf("user parts = %d, want text plus three media parts: %#v", len(parts), parts)
|
||||
}
|
||||
if text, ok := parts[0].(chat.TextPart); !ok || text.Text != "what is this?" {
|
||||
t.Errorf("part 0 = %#v, want the caption text", parts[0])
|
||||
}
|
||||
image, ok := parts[1].(chat.ImagePart)
|
||||
if !ok || string(image.Data) != "png-bytes" || image.MediaType != "image/png" {
|
||||
t.Errorf("part 1 = %#v, want an image part carrying the png bytes", parts[1])
|
||||
}
|
||||
linked, ok := parts[2].(chat.ImagePart)
|
||||
if !ok || linked.URL != "https://example.invalid/pic.jpg" {
|
||||
t.Errorf("part 2 = %#v, want an image part pointing at the URL", parts[2])
|
||||
}
|
||||
file, ok := parts[3].(chat.FilePart)
|
||||
if !ok {
|
||||
t.Fatalf("part 3 = %#v, want a file part", parts[3])
|
||||
}
|
||||
if string(file.Data) != "pdf-bytes" || file.MediaType != "application/pdf" || file.Name != "report.pdf" {
|
||||
t.Errorf("file part = %#v, want the pdf bytes with type and name", file)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildTurnMessagesSkipsUndeliverableMedia: an attachment carrying
|
||||
// neither bytes nor a URL names nothing the model can consume, so it must
|
||||
// be dropped rather than sent as an empty part.
|
||||
func TestBuildTurnMessagesSkipsUndeliverableMedia(t *testing.T) {
|
||||
request := gateway.TurnModelRequest{
|
||||
Messages: []gateway.CompressedMessage{
|
||||
{Role: "user", Content: "look"},
|
||||
},
|
||||
Media: []gateway.MediaAttachment{
|
||||
{Type: "video"},
|
||||
{Type: "image", MIMEType: "image/png", Data: []byte("png")},
|
||||
},
|
||||
}
|
||||
messages := buildTurnMessages(request)
|
||||
fileSeen := false
|
||||
for _, p := range messages[0].Parts {
|
||||
if _, ok := p.(chat.FilePart); ok {
|
||||
fileSeen = true
|
||||
}
|
||||
}
|
||||
if fileSeen {
|
||||
t.Errorf("parts = %#v, want the empty attachment dropped", messages[0].Parts)
|
||||
}
|
||||
if len(messages[0].Parts) != 2 {
|
||||
t.Fatalf("user parts = %d, want text plus the one deliverable image", len(messages[0].Parts))
|
||||
}
|
||||
if text, ok := messages[0].Parts[0].(chat.TextPart); !ok || text.Text != "look" {
|
||||
t.Errorf("part 0 = %#v, want the text part", messages[0].Parts[0])
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildTurnMessagesWithoutMediaKeepsPlainContent is the regression
|
||||
// guard for the overwhelmingly common case: text-only turns stay exactly as
|
||||
// they were, with Content and no parts.
|
||||
func TestBuildTurnMessagesWithoutMediaKeepsPlainContent(t *testing.T) {
|
||||
request := gateway.TurnModelRequest{
|
||||
Messages: []gateway.CompressedMessage{
|
||||
{Role: "system", Content: "sys"},
|
||||
{Role: "user", Content: "plain"},
|
||||
{Role: "assistant", Content: "reply"},
|
||||
},
|
||||
}
|
||||
messages := buildTurnMessages(request)
|
||||
for i, want := range []struct {
|
||||
role chat.Role
|
||||
content string
|
||||
}{
|
||||
{chat.RoleSystem, "sys"},
|
||||
{chat.RoleUser, "plain"},
|
||||
{chat.RoleAssistant, "reply"},
|
||||
} {
|
||||
if messages[i].Content != want.content || messages[i].Parts != nil {
|
||||
t.Errorf("message %d = %#v, want content %q and no parts", i, messages[i], want.content)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestStartGatewayRuntimeSetsUpMemoryBeforeGatewayChat pins the ordering
|
||||
// docs/prds/memory-engine-unification.md §4's "Prerequisite" note requires.
|
||||
// startGatewayRuntime (gateway.go) constructs the only chat turn runner in
|
||||
// production via setupGatewayChat, and a turn runner captures b.memEngines at
|
||||
// construction time via boot.memoryStore(). Built the other way round it
|
||||
// captures a nil engine and the chat <memory> block never appears, silently,
|
||||
// because renderMemory treats a nil engine the same as a failed read. Nothing
|
||||
// at runtime observes the order, so it is asserted by source position, the
|
||||
// same way TestSetupBackendsRegistersContainerCleanupAfterNATS in
|
||||
// bootstrap_nats_test.go pins cleanup ordering for the same reason.
|
||||
func TestStartGatewayRuntimeSetsUpMemoryBeforeGatewayChat(t *testing.T) {
|
||||
fileset := token.NewFileSet()
|
||||
file, err := parser.ParseFile(fileset, "gateway.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run := methodBody(t, file, "startGatewayRuntime")
|
||||
memoryEngine := methodCallPosition(run, "setupMemoryEngine")
|
||||
chat := methodCallPosition(run, "setupGatewayChat")
|
||||
if memoryEngine == token.NoPos || chat == token.NoPos {
|
||||
t.Fatalf("startGatewayRuntime call positions: setupMemoryEngine=%v setupGatewayChat=%v, want both present", memoryEngine, chat)
|
||||
}
|
||||
if chat < memoryEngine {
|
||||
t.Fatal("startGatewayRuntime wires setupGatewayChat before setupMemoryEngine; the turn runner would capture a nil memory engine")
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
|
||||
// TestPublishedProjectionAgreesWithFrontEndsOnConfiguredChannels: "is a chat
|
||||
// channel configured" is answered twice -- once by config.ChatConfig.FrontEnds,
|
||||
// which the channel status surface on /api/channels is built from, and once by
|
||||
// the ChatView.ChannelConfigured boolean this process publishes for the
|
||||
// dashboard's setup checklist. A deployment that FrontEnds calls configured
|
||||
// must not be told by the checklist to connect a channel it already has. Both
|
||||
// sides derive from that one definition; this test is what keeps them from
|
||||
// being re-decided separately.
|
||||
func TestPublishedProjectionAgreesWithFrontEndsOnConfiguredChannels(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
cfg config.Config
|
||||
}{
|
||||
{name: "nothing configured", cfg: config.Config{}},
|
||||
{
|
||||
name: "telegram token",
|
||||
cfg: config.Config{Chat: config.ChatConfig{
|
||||
Telegram: config.TelegramConfig{Token: config.SecretRef{Engine: "env", Key: "TELEGRAM_TOKEN"}},
|
||||
}},
|
||||
},
|
||||
{
|
||||
name: "telegram token through the secret engine",
|
||||
cfg: config.Config{Chat: config.ChatConfig{
|
||||
Telegram: config.TelegramConfig{Token: config.SecretRef{Engine: "builtin", Key: "telegram"}},
|
||||
}},
|
||||
},
|
||||
{
|
||||
name: "webhook gateway",
|
||||
cfg: config.Config{Chat: config.ChatConfig{WebhookAddr: "127.0.0.1:9099"}},
|
||||
},
|
||||
{
|
||||
name: "inbound mail gateway",
|
||||
cfg: config.Config{Chat: config.ChatConfig{Email: config.EmailConfig{ListenAddr: "127.0.0.1:2525"}}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
b := &boot{
|
||||
cfg: tc.cfg,
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
stateStore: st,
|
||||
cfgHolder: config.NewHolder(tc.cfg),
|
||||
}
|
||||
b.setupObservability(t.Context())
|
||||
|
||||
// What the dashboard's /api/channels page is built from.
|
||||
frontEndsSayConfigured := false
|
||||
for _, frontEnd := range tc.cfg.Chat.FrontEnds() {
|
||||
if frontEnd.Configured {
|
||||
frontEndsSayConfigured = true
|
||||
}
|
||||
}
|
||||
|
||||
// What the dashboard's setup checklist reads, through the
|
||||
// same round trip a reading process performs.
|
||||
document, err := json.Marshal(webui.BuildConfigView(b.configViewInput(t.Context())))
|
||||
if err != nil {
|
||||
t.Fatalf("render the published projection: %v", err)
|
||||
}
|
||||
var published webui.ConfigView
|
||||
if err := json.Unmarshal(document, &published); err != nil {
|
||||
t.Fatalf("decode the published projection: %v", err)
|
||||
}
|
||||
|
||||
if published.Chat.ChannelConfigured != frontEndsSayConfigured {
|
||||
t.Errorf("published Chat.ChannelConfigured = %v, but ChatConfig.FrontEnds reports a configured front-end = %v (%+v)",
|
||||
published.Chat.ChannelConfigured, frontEndsSayConfigured, published.Chat)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
|
||||
// TestPublishConfigSnapshotRendersTheDaemonsConfiguration: the daemon is the
|
||||
// configuration owner, so it is the process that renders the dashboard's
|
||||
// projection and publishes it for the UI process to read. It builds that view
|
||||
// from its own state rather than from a webui.Server it never serves
|
||||
// (archie-core-ml30).
|
||||
func TestPublishConfigSnapshotRendersTheDaemonsConfiguration(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
cfg := config.Config{
|
||||
BotUser: "archie-bot",
|
||||
Repos: []config.Repo{{Owner: "acme", Name: "widget", Base: "main"}},
|
||||
Chat: config.ChatConfig{
|
||||
Operator: "Sam",
|
||||
ShowToolCalls: true,
|
||||
WebhookAddr: "127.0.0.1:9099",
|
||||
},
|
||||
}
|
||||
b := &boot{
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
stateStore: st,
|
||||
cfgHolder: config.NewHolder(cfg),
|
||||
lastReload: func() config.ReloadStatus {
|
||||
return config.ReloadStatus{LastError: "poll_interval must be positive"}
|
||||
},
|
||||
}
|
||||
b.currentProvenance.Store(&configuration.Provenance{Origins: []configuration.Origin{
|
||||
{Path: "/etc/archie/config.toml", Role: configuration.RoleMain, Layer: configuration.LayerBase},
|
||||
}})
|
||||
|
||||
b.publishConfigSnapshot(t.Context())
|
||||
|
||||
snapshot, found, err := st.ConfigSnapshot(context.Background())
|
||||
if err != nil || !found {
|
||||
t.Fatalf("ConfigSnapshot = (found %v, %v), want the published document", found, err)
|
||||
}
|
||||
if snapshot.Schema != webui.ConfigViewSchema {
|
||||
t.Fatalf("Schema = %q, want %q", snapshot.Schema, webui.ConfigViewSchema)
|
||||
}
|
||||
|
||||
var view webui.ConfigView
|
||||
if err := json.Unmarshal(snapshot.Document, &view); err != nil {
|
||||
t.Fatalf("decode published document: %v", err)
|
||||
}
|
||||
if view.Identity.BotUser != "archie-bot" || len(view.Repositories) != 1 {
|
||||
t.Errorf("view = %+v, want the daemon's identity and repositories", view)
|
||||
}
|
||||
// The chat page and the setup checklist are rendered by a process that
|
||||
// holds no configuration, so the projection has to carry what they read.
|
||||
if !view.Chat.ShowToolCalls {
|
||||
t.Error("Chat.ShowToolCalls = false; the chat page would never expand tool calls")
|
||||
}
|
||||
if view.Chat.Operator != "Sam" {
|
||||
t.Errorf("Chat.Operator = %q, want Sam", view.Chat.Operator)
|
||||
}
|
||||
if !view.Chat.ChannelConfigured {
|
||||
t.Error("Chat.ChannelConfigured = false despite a configured webhook address")
|
||||
}
|
||||
if len(view.Provenance) != 1 || view.Provenance[0].Path != "/etc/archie/config.toml" {
|
||||
t.Errorf("Provenance = %+v, want the daemon's file chain", view.Provenance)
|
||||
}
|
||||
if view.Reload == nil || view.Reload.LastError != "poll_interval must be positive" {
|
||||
t.Errorf("Reload = %+v, want the last reload outcome", view.Reload)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishedSnapshotCarriesPerIdentityForges(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
b := &boot{
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
stateStore: st,
|
||||
cfgHolder: config.NewHolder(config.Config{
|
||||
BotUser: "archie-bot",
|
||||
Forge: config.Forge{Type: "github", Host: "https://github.example"},
|
||||
Repos: []config.Repo{{Owner: "acme", Name: "widget", Base: "main"}},
|
||||
Identities: []config.IdentityConfig{
|
||||
{
|
||||
Name: "gitea-bot", BotUser: "archie-gitea",
|
||||
Forge: config.Forge{Type: "gitea", Host: "https://gitea.example"},
|
||||
Repos: []config.Repo{{Owner: "beta", Name: "svc", Base: "main"}},
|
||||
},
|
||||
},
|
||||
}),
|
||||
}
|
||||
b.publishConfigSnapshot(t.Context())
|
||||
|
||||
snapshot, found, err := st.ConfigSnapshot(context.Background())
|
||||
if err != nil || !found {
|
||||
t.Fatalf("ConfigSnapshot = (found %v, %v), want the published document", found, err)
|
||||
}
|
||||
var view webui.ConfigView
|
||||
if err := json.Unmarshal(snapshot.Document, &view); err != nil {
|
||||
t.Fatalf("decode published document: %v", err)
|
||||
}
|
||||
if !view.MultiIdentity {
|
||||
t.Error("MultiIdentity = false with a configured identity")
|
||||
}
|
||||
if len(view.Identities) != 1 {
|
||||
t.Fatalf("Identities = %+v, want the configured identity", view.Identities)
|
||||
}
|
||||
got := view.Identities[0]
|
||||
if got.Name != "gitea-bot" || got.ForgeType != "gitea" || got.ForgeHost != "https://gitea.example" {
|
||||
t.Errorf("Identities[0] = %+v, want the gitea-bot forge coordinates", got)
|
||||
}
|
||||
if len(got.Repos) != 1 || got.Repos[0].Owner != "beta" || got.Repos[0].Name != "svc" {
|
||||
t.Errorf("Identities[0].Repos = %+v, want the repositories it owns", got.Repos)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishConfigSnapshotWithoutConfiguration: called before the daemon has
|
||||
// a configuration Holder, publishing is a no-op rather than a panic.
|
||||
func TestPublishConfigSnapshotWithoutConfiguration(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
b := &boot{log: slog.New(slog.DiscardHandler), stateStore: st}
|
||||
b.publishConfigSnapshot(t.Context())
|
||||
|
||||
if _, found, err := st.ConfigSnapshot(context.Background()); found || err != nil {
|
||||
t.Fatalf("ConfigSnapshot = (found %v, %v), want nothing published", found, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLiveSettingsApplyRepublishesTheConfigSnapshot: the dashboard renders the
|
||||
// published projection, not the daemon's Holder, so a live apply that changes
|
||||
// the running config must republish it or the page keeps showing the old
|
||||
// values until the next reload.
|
||||
func TestLiveSettingsApplyRepublishesTheConfigSnapshot(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
b, _ := newLiveApplyBoot(t, fileConfig())
|
||||
b.stateStore = st
|
||||
if err := b.applyWorkflowExecutionSettings(t.Context(), workflow.ExecutionSettings{MaxModelToolSteps: 25, MaxRuntime: time.Hour, MaxConsecutiveGateFailures: 4}, 2); err != nil {
|
||||
t.Fatalf("live update: %v", err)
|
||||
}
|
||||
|
||||
snapshot, found, err := st.ConfigSnapshot(context.Background())
|
||||
if err != nil || !found {
|
||||
t.Fatalf("ConfigSnapshot = (found %v, %v), want the live apply to publish one", found, err)
|
||||
}
|
||||
var view webui.ConfigView
|
||||
if err := json.Unmarshal(snapshot.Document, &view); err != nil {
|
||||
t.Fatalf("decode published document: %v", err)
|
||||
}
|
||||
if view.Budgets.MaxSteps != 25 || view.Budgets.GateMaxFailures != 4 {
|
||||
t.Errorf("published budgets = %+v, want the live-applied limits", view.Budgets)
|
||||
}
|
||||
}
|
||||
@@ -1,374 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/applystatus"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
)
|
||||
|
||||
// The limits this package's fixtures boot or run with, and the documents the
|
||||
// control plane stores them as. Named so a test that asserts "the running
|
||||
// limits stayed" and a test that asserts "the update was applied" cannot
|
||||
// disagree about what "running" means.
|
||||
var (
|
||||
bootedSettings = workflow.ExecutionSettings{MaxModelToolSteps: 10, MaxRuntime: 5 * time.Minute, MaxConsecutiveGateFailures: 3, MaxTaskRuntime: 4 * time.Hour}
|
||||
bootedDocument = `{"max_model_tool_steps": 10, "max_runtime_seconds": 300, "max_consecutive_gate_failures": 3}`
|
||||
)
|
||||
|
||||
// applyStatusRecorder is the State Store end of the apply-status surface: it
|
||||
// keeps what a process reported, so a test can assert what the settings page
|
||||
// would render.
|
||||
type applyStatusRecorder struct {
|
||||
mu sync.Mutex
|
||||
writes []storecontract.ApplyStatus
|
||||
}
|
||||
|
||||
func (r *applyStatusRecorder) PutApplyStatus(_ context.Context, status storecontract.ApplyStatus) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.writes = append(r.writes, status)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *applyStatusRecorder) ListApplyStatus(context.Context) ([]storecontract.ApplyStatus, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return append([]storecontract.ApplyStatus(nil), r.writes...), nil
|
||||
}
|
||||
|
||||
// last returns the most recent record written for kind.
|
||||
func (r *applyStatusRecorder) last(kind string) (storecontract.ApplyStatus, bool) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
for _, v := range slices.Backward(r.writes) {
|
||||
if v.Kind == kind {
|
||||
return v, true
|
||||
}
|
||||
}
|
||||
return storecontract.ApplyStatus{}, false
|
||||
}
|
||||
|
||||
// awaitCount waits until n records have been written for kind. The live apply
|
||||
// runs on the watch goroutine, so a test that drives it through the stream has
|
||||
// nothing to synchronise on but the record it is waiting for.
|
||||
func (r *applyStatusRecorder) awaitCount(t *testing.T, kind string, n int) []storecontract.ApplyStatus {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
r.mu.Lock()
|
||||
written := make([]storecontract.ApplyStatus, 0, n)
|
||||
for _, status := range r.writes {
|
||||
if status.Kind == kind {
|
||||
written = append(written, status)
|
||||
}
|
||||
}
|
||||
r.mu.Unlock()
|
||||
if len(written) >= n {
|
||||
return written
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("%s: %d records reported, want %d", kind, len(written), n)
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// newLiveApplyBoot builds a boot running the given snapshot, whose apply status
|
||||
// reports land in a recorder.
|
||||
func newLiveApplyBoot(t *testing.T, running config.Config) (*boot, *applyStatusRecorder) {
|
||||
t.Helper()
|
||||
recorder := &applyStatusRecorder{}
|
||||
b := &boot{
|
||||
cfg: running,
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
cfgHolder: config.NewHolder(running),
|
||||
processName: applystatus.Daemon,
|
||||
}
|
||||
b.applyStatus = applystatus.New(b.processName, recorder, b.log)
|
||||
return b, recorder
|
||||
}
|
||||
|
||||
// settingsWatchStub answers Query with one stored settings document and Watch
|
||||
// with a stream carrying the given documents. It is the seam the daemon really
|
||||
// meets a live update through: the control plane stores documents, and
|
||||
// controlplane.Client decodes them before the apply path sees anything.
|
||||
type settingsWatchStub struct {
|
||||
stored string
|
||||
version int64
|
||||
documents []string
|
||||
}
|
||||
|
||||
func (*settingsWatchStub) Catalog(context.Context, *pb.CatalogRequest, ...grpc.CallOption) (*pb.CatalogResponse, error) {
|
||||
return &pb.CatalogResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *settingsWatchStub) Query(context.Context, *pb.QueryRequest, ...grpc.CallOption) (*pb.QueryResponse, error) {
|
||||
return &pb.QueryResponse{Resource: &pb.Resource{Kind: controlplane.WorkflowExecutionSettingsKind, Version: s.version, ValueJson: []byte(s.stored)}}, nil
|
||||
}
|
||||
|
||||
func (*settingsWatchStub) History(context.Context, *pb.HistoryRequest, ...grpc.CallOption) (*pb.HistoryResponse, error) {
|
||||
panic("unexpected History")
|
||||
}
|
||||
|
||||
func (*settingsWatchStub) Audit(context.Context, *pb.AuditRequest, ...grpc.CallOption) (*pb.AuditResponse, error) {
|
||||
return &pb.AuditResponse{}, nil
|
||||
}
|
||||
|
||||
func (*settingsWatchStub) Command(context.Context, *pb.CommandRequest, ...grpc.CallOption) (*pb.CommandResponse, error) {
|
||||
panic("unexpected Command")
|
||||
}
|
||||
|
||||
func (s *settingsWatchStub) Watch(ctx context.Context, request *pb.WatchRequest, _ ...grpc.CallOption) (grpc.ServerStreamingClient[pb.WatchResponse], error) {
|
||||
_ = request
|
||||
responses := make([]*pb.WatchResponse, 0, len(s.documents))
|
||||
for i, document := range s.documents {
|
||||
responses = append(responses, &pb.WatchResponse{Resource: &pb.Resource{
|
||||
Kind: controlplane.WorkflowExecutionSettingsKind,
|
||||
Version: s.version + int64(i) + 1,
|
||||
ValueJson: []byte(document),
|
||||
}})
|
||||
}
|
||||
return &watchStreamStub{responses: responses, done: ctx.Done()}, nil
|
||||
}
|
||||
|
||||
// watchStreamStub is the client end of a Watch stream. Recv is the only method
|
||||
// the settings watch calls; the embedded ClientStream is nil, so any other call
|
||||
// panics rather than pretending to work.
|
||||
type watchStreamStub struct {
|
||||
grpc.ClientStream
|
||||
responses []*pb.WatchResponse
|
||||
done <-chan struct{}
|
||||
next int
|
||||
// onDeliver, when set, runs as the stream delivers each response, so a
|
||||
// stub standing in for the store can store what it just delivered.
|
||||
onDeliver func()
|
||||
}
|
||||
|
||||
func (s *watchStreamStub) Recv() (*pb.WatchResponse, error) {
|
||||
if s.next >= len(s.responses) {
|
||||
if s.done == nil {
|
||||
return nil, io.EOF
|
||||
}
|
||||
<-s.done
|
||||
return nil, context.Canceled
|
||||
}
|
||||
response := s.responses[s.next]
|
||||
s.next++
|
||||
if s.onDeliver != nil {
|
||||
s.onDeliver()
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
// TestLiveExecutionSettingsUpdateIsCheckedBeforeItReplacesTheRunningLimits is
|
||||
// archie-core-nwa0. docs/prds/runtime-control-plane.md ("API") requires a live
|
||||
// change to replace a running component only after the new one has been
|
||||
// started and checked; if the check fails the old one keeps running. A live
|
||||
// workflow-execution-settings update replaces the configuration snapshot every
|
||||
// new task is built from, so a candidate whose snapshot this process cannot run
|
||||
// must leave the running limits and the running snapshot in place, and the
|
||||
// failure must reach the apply-status surface carrying the version that is
|
||||
// still live.
|
||||
func TestLiveExecutionSettingsUpdateIsCheckedBeforeItReplacesTheRunningLimits(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
candidate workflow.ExecutionSettings
|
||||
wantRunning workflow.ExecutionSettings
|
||||
wantVersion int64
|
||||
}{
|
||||
{
|
||||
name: "an update whose snapshot this process can run replaces the running limits",
|
||||
candidate: workflow.ExecutionSettings{MaxModelToolSteps: 25, MaxRuntime: time.Hour, MaxConsecutiveGateFailures: 4},
|
||||
wantRunning: workflow.ExecutionSettings{MaxModelToolSteps: 25, MaxRuntime: time.Hour, MaxConsecutiveGateFailures: 4},
|
||||
wantVersion: 2,
|
||||
},
|
||||
{
|
||||
// Zero is the documented "this individual limit is off", so an
|
||||
// all-zero update is a legal live change, not a rejection, and the
|
||||
// check must not invent a bound the store does not enforce.
|
||||
name: "an update that disables every limit is accepted",
|
||||
candidate: workflow.ExecutionSettings{},
|
||||
wantRunning: workflow.ExecutionSettings{},
|
||||
wantVersion: 2,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
b, status := newLiveApplyBoot(t, fileConfig())
|
||||
if err := b.applyWorkflowExecutionSettings(t.Context(), bootedSettings, 1); err != nil {
|
||||
t.Fatalf("applying the running settings: %v", err)
|
||||
}
|
||||
if err := b.applyWorkflowExecutionSettings(t.Context(), tt.candidate, 2); err != nil {
|
||||
t.Fatalf("live update: %v", err)
|
||||
}
|
||||
|
||||
got := b.executionSettings.Load()
|
||||
if got == nil {
|
||||
t.Fatal("no settings are recorded as running")
|
||||
}
|
||||
if *got != tt.wantRunning {
|
||||
t.Errorf("running settings = %+v, want %+v", *got, tt.wantRunning)
|
||||
}
|
||||
|
||||
// The snapshot a new task is built from has to move with the
|
||||
// settings: it is the half of the component the daemon runs.
|
||||
wantBudgets := budgetsFor(tt.wantRunning)
|
||||
if budgets := b.cfgHolder.Get().Budgets; budgets != wantBudgets {
|
||||
t.Errorf("running budgets = %+v, want %+v", budgets, wantBudgets)
|
||||
}
|
||||
|
||||
last, ok := status.last(controlplane.WorkflowExecutionSettingsKind)
|
||||
if !ok {
|
||||
t.Fatal("the live update reported no apply status")
|
||||
}
|
||||
if last.AppliedVersion != tt.wantVersion {
|
||||
t.Errorf("apply status version = %d, want %d", last.AppliedVersion, tt.wantVersion)
|
||||
}
|
||||
if last.Error != "" {
|
||||
t.Errorf("apply status error = %q, want none for an applied update", last.Error)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLiveExecutionSettingsUpdateIsRefusedWhenTheSnapshotIsNotRunnable covers
|
||||
// the refusal half of the same check. The candidate is the running snapshot
|
||||
// with new limits written into it, and configuration.Validate does not read
|
||||
// limits, so the only input that can fail the check is a snapshot this process
|
||||
// would not run -- which is what this test's daemon is running. A live update
|
||||
// must not publish a snapshot this process cannot run, must leave the component
|
||||
// it would have replaced in place, and must report the refusal against the
|
||||
// version still live.
|
||||
func TestLiveExecutionSettingsUpdateIsRefusedWhenTheSnapshotIsNotRunnable(t *testing.T) {
|
||||
unrunnable := fileConfig()
|
||||
unrunnable.Containers.Image = ""
|
||||
applyExecutionBudgets(&unrunnable, bootedSettings)
|
||||
b, status := newLiveApplyBoot(t, unrunnable)
|
||||
// The daemon is already running these limits. Seeded directly rather than
|
||||
// applied: the ordinary apply refuses this snapshot too, which is the point
|
||||
// of the check.
|
||||
b.executionSettings.Store(&bootedSettings)
|
||||
b.applyStatus.Report(t.Context(), controlplane.WorkflowExecutionSettingsKind, 1, nil)
|
||||
|
||||
budgets := budgetsFor(bootedSettings)
|
||||
update := workflow.ExecutionSettings{MaxModelToolSteps: 25, MaxRuntime: time.Hour, MaxConsecutiveGateFailures: 4}
|
||||
if err := b.applyWorkflowExecutionSettings(t.Context(), update, 2); err == nil {
|
||||
t.Fatal("an update whose snapshot this process cannot run was applied")
|
||||
}
|
||||
|
||||
if got := b.executionSettings.Load(); got == nil || *got != bootedSettings {
|
||||
t.Errorf("running settings = %v, want the refused update to leave %+v running", got, bootedSettings)
|
||||
}
|
||||
if got := b.cfgHolder.Get().Budgets; got != budgets {
|
||||
t.Errorf("running budgets = %+v, want the refused update to leave %+v running", got, budgets)
|
||||
}
|
||||
|
||||
last, ok := status.last(controlplane.WorkflowExecutionSettingsKind)
|
||||
if !ok {
|
||||
t.Fatal("the refused update reported no apply status")
|
||||
}
|
||||
if last.Error == "" {
|
||||
t.Error("the refusal was not reported through apply status")
|
||||
}
|
||||
if last.AppliedVersion != 1 {
|
||||
t.Errorf("apply status version = %d, want the version still live (1)", last.AppliedVersion)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLiveExecutionSettingsRefusalIsReportedThroughTheClient is the other half
|
||||
// of the same item, over the seam the daemon actually meets a refusal through.
|
||||
// controlplane.Client decodes every document it is handed, so an update this
|
||||
// process cannot run arrives as a watch error, never as invalid settings: the
|
||||
// watch branch must report that refusal against the version still live instead
|
||||
// of only logging it, or the settings page shows a live resource as healthy
|
||||
// while nothing has been applied. (The stream does not stay ended: the watch
|
||||
// re-establishes it, which control_plane_watch_test.go covers. This stub
|
||||
// answers every re-established stream with the same documents, so this test
|
||||
// reads the record the refusal wrote rather than counting how often it was
|
||||
// written.)
|
||||
func TestLiveExecutionSettingsRefusalIsReportedThroughTheClient(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
document string
|
||||
wantRunning workflow.ExecutionSettings
|
||||
wantVersion int64
|
||||
wantErrorContains string
|
||||
}{
|
||||
{
|
||||
name: "an update the process can run is applied",
|
||||
document: `{"max_model_tool_steps": 25, "max_runtime_seconds": 3600, "max_consecutive_gate_failures": 4}`,
|
||||
wantRunning: workflow.ExecutionSettings{MaxModelToolSteps: 25, MaxRuntime: time.Hour, MaxConsecutiveGateFailures: 4, MaxTaskRuntime: 4 * time.Hour},
|
||||
wantVersion: 2,
|
||||
},
|
||||
{
|
||||
name: "an update the client refuses is reported against the version still live",
|
||||
document: `{"max_model_tool_steps": -1, "max_runtime_seconds": 3600, "max_consecutive_gate_failures": 4}`,
|
||||
wantRunning: bootedSettings,
|
||||
wantVersion: 1,
|
||||
wantErrorContains: "max model/tool steps must not be negative",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
b, status := newLiveApplyBoot(t, fileConfig())
|
||||
b.controlPlane = controlplane.NewRPCClient(&settingsWatchStub{stored: bootedDocument, version: 1, documents: []string{tt.document}})
|
||||
|
||||
if err := b.startWorkflowExecutionSettings(t.Context()); err != nil {
|
||||
t.Fatalf("startWorkflowExecutionSettings: %v", err)
|
||||
}
|
||||
// One record for boot, one for the watched update.
|
||||
records := status.awaitCount(t, controlplane.WorkflowExecutionSettingsKind, 2)
|
||||
|
||||
got := b.executionSettings.Load()
|
||||
if got == nil {
|
||||
t.Fatal("no settings are recorded as running")
|
||||
}
|
||||
if *got != tt.wantRunning {
|
||||
t.Errorf("running settings = %+v, want %+v", *got, tt.wantRunning)
|
||||
}
|
||||
if budgets := b.cfgHolder.Get().Budgets; budgets != budgetsFor(tt.wantRunning) {
|
||||
t.Errorf("running budgets = %+v, want %+v", budgets, budgetsFor(tt.wantRunning))
|
||||
}
|
||||
|
||||
last := records[len(records)-1]
|
||||
if last.AppliedVersion != tt.wantVersion {
|
||||
t.Errorf("apply status version = %d, want %d", last.AppliedVersion, tt.wantVersion)
|
||||
}
|
||||
if tt.wantErrorContains == "" && last.Error != "" {
|
||||
t.Errorf("apply status error = %q, want none for an applied update", last.Error)
|
||||
}
|
||||
if tt.wantErrorContains != "" && !strings.Contains(last.Error, tt.wantErrorContains) {
|
||||
t.Errorf("apply status error = %q, want it to carry %q", last.Error, tt.wantErrorContains)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// budgetsFor is the configuration snapshot a set of limits produces. Named so
|
||||
// the tests and applyExecutionBudgets cannot drift on the mapping.
|
||||
func budgetsFor(settings workflow.ExecutionSettings) config.Budgets {
|
||||
return config.Budgets{
|
||||
MaxSteps: settings.MaxModelToolSteps,
|
||||
WallClock: config.Duration(settings.MaxRuntime),
|
||||
GateMaxFailures: settings.MaxConsecutiveGateFailures,
|
||||
TaskWallClock: config.Duration(settings.MaxTaskRuntime),
|
||||
}
|
||||
}
|
||||
@@ -1,203 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
// controlPlaneStub answers Query from a fixed resource map. queryErr, when
|
||||
// set, fails every Query so a test can drive the unreachable-State-Store
|
||||
// path. A kind the map does not carry is answered the way the server answers
|
||||
// one with no stored value -- codes.NotFound (controlplane.mapError) -- so a
|
||||
// test can drive the absent-resource state a skipped seed leaves behind.
|
||||
type controlPlaneStub struct {
|
||||
values map[string]any
|
||||
queryErr error
|
||||
}
|
||||
|
||||
func (*controlPlaneStub) Catalog(context.Context, *pb.CatalogRequest, ...grpc.CallOption) (*pb.CatalogResponse, error) {
|
||||
return &pb.CatalogResponse{}, nil
|
||||
}
|
||||
|
||||
func (c *controlPlaneStub) Query(_ context.Context, request *pb.QueryRequest, _ ...grpc.CallOption) (*pb.QueryResponse, error) {
|
||||
if c.queryErr != nil {
|
||||
return nil, c.queryErr
|
||||
}
|
||||
value, ok := c.values[request.Kind]
|
||||
if !ok {
|
||||
return nil, status.Error(codes.NotFound, "resource not found")
|
||||
}
|
||||
encoded, err := json.Marshal(value)
|
||||
return &pb.QueryResponse{Resource: &pb.Resource{Kind: request.Kind, Version: 3, ValueJson: encoded}}, err
|
||||
}
|
||||
|
||||
func (*controlPlaneStub) History(context.Context, *pb.HistoryRequest, ...grpc.CallOption) (*pb.HistoryResponse, error) {
|
||||
panic("unexpected History")
|
||||
}
|
||||
|
||||
func (*controlPlaneStub) Audit(context.Context, *pb.AuditRequest, ...grpc.CallOption) (*pb.AuditResponse, error) {
|
||||
return &pb.AuditResponse{}, nil
|
||||
}
|
||||
|
||||
func (*controlPlaneStub) Command(context.Context, *pb.CommandRequest, ...grpc.CallOption) (*pb.CommandResponse, error) {
|
||||
panic("unexpected Command")
|
||||
}
|
||||
|
||||
func (*controlPlaneStub) Watch(context.Context, *pb.WatchRequest, ...grpc.CallOption) (grpc.ServerStreamingClient[pb.WatchResponse], error) {
|
||||
panic("unexpected Watch")
|
||||
}
|
||||
|
||||
// databaseOwnedResources is a control-plane projection whose every value
|
||||
// differs from fileConfig below, so any field that comes back with the file
|
||||
// value after a reload is a field the reload reverted.
|
||||
func databaseOwnedResources() map[string]any {
|
||||
return map[string]any{
|
||||
controlplane.ProviderSettingsKind: map[string]any{"main": map[string]any{"class": "openai", "base_url": "https://db.example.com"}},
|
||||
controlplane.ModelRoleAssignmentsKind: map[string]string{"builder": "main/db-model"},
|
||||
controlplane.RepositoryPoliciesKind: []config.Repo{{Owner: "acme", Name: "from-database"}},
|
||||
controlplane.ChannelSettingsKind: map[string]any{"operator": "database", "max_steps": 20, "models": []string{"main/db-model"}, "email": map[string]any{}, "webhook": map[string]any{}, "telegram": map[string]any{"allowed_user_ids": []int64{42}}, "rate_limit": map[string]any{}, "workspace": "/workspace"},
|
||||
controlplane.SchedulingPolicyKind: map[string]any{"poll_interval": "2m", "max_retries": 7, "dispatch": map[string]any{"trigger": "assignee"}},
|
||||
controlplane.ToolSettingsKind: map[string]any{"mcp_servers": []map[string]any{}, "policy": map[string]any{}, "web_fetch": map[string]any{}, "minimax": map[string]any{}},
|
||||
controlplane.PluginSettingsKind: map[string]any{"plugin_dir": "/db/plugins", "module_dir": "/db/modules", "secret_engine_dir": "/db/secrets", "skills_dir": "/db/skills"},
|
||||
controlplane.ContainerRuntimePoliciesKind: config.ContainerConfig{Image: "archie:from-database", PullPolicy: "missing"},
|
||||
}
|
||||
}
|
||||
|
||||
// fileConfig is what the loader produces from config.toml alone: the layer a
|
||||
// SIGHUP reload re-resolves, holding none of the database's values. It is a
|
||||
// config the daemon would run, so it passes configuration.Validate -- the live
|
||||
// apply path runs that same check over the snapshot it is about to publish --
|
||||
// and every field validation reads is filled in the way the loader's defaults
|
||||
// fill it, so a kind with no stored value can fall back to this document (see
|
||||
// TestRuntimeConfigKeepsTheFileValueWhenAKindHasNoStoredResource).
|
||||
func fileConfig() config.Config {
|
||||
return config.Config{
|
||||
BotUser: "widget",
|
||||
Forge: config.Forge{Type: "github"},
|
||||
Dispatch: config.Dispatch{Trigger: "assignee"},
|
||||
Providers: map[string]config.Provider{"file": {Class: "openai"}},
|
||||
Models: map[string]string{"builder": "file/model"},
|
||||
Repos: []config.Repo{{Owner: "acme", Name: "from-file"}},
|
||||
Chat: config.ChatConfig{Operator: "file"},
|
||||
PollInterval: config.Duration(time.Minute),
|
||||
MaxRetries: 1,
|
||||
PluginDir: "/file/plugins",
|
||||
Containers: config.ContainerConfig{Image: "archie:from-file", PullPolicy: "missing"},
|
||||
Budgets: config.Budgets{MaxSteps: 1, WallClock: config.Duration(time.Minute)},
|
||||
}
|
||||
}
|
||||
|
||||
func newReloadBoot(t *testing.T, stub *controlPlaneStub) *boot {
|
||||
t.Helper()
|
||||
b := &boot{
|
||||
cfg: fileConfig(),
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
controlPlane: controlplane.NewRPCClient(stub),
|
||||
}
|
||||
b.cfgHolder = config.NewHolder(b.cfg)
|
||||
return b
|
||||
}
|
||||
|
||||
func TestRuntimeConfigResolvesStoredProviderReferences(t *testing.T) {
|
||||
for _, providerID := range []string{"main", "secondary"} {
|
||||
t.Run(providerID, func(t *testing.T) {
|
||||
refKey := "ARCHIE_TEST_STORED_PROVIDER_" + strings.ToUpper(providerID)
|
||||
t.Setenv(refKey, "provider-secret")
|
||||
resources := databaseOwnedResources()
|
||||
resources[controlplane.ProviderSettingsKind] = map[string]any{providerID: map[string]any{
|
||||
"class": "openai", "api_key_ref": map[string]any{"engine": "env", "key": refKey},
|
||||
}}
|
||||
b := newReloadBoot(t, &controlPlaneStub{values: resources})
|
||||
b.secrets = secret.NewRegistry()
|
||||
if err := b.loadRuntimeConfig(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := b.cfgHolder.Get().Providers[providerID]
|
||||
if got.APIKey != (secret.SecretRef{}) || got.APIKeyEnv != providerSecretEnvName("root", providerID) {
|
||||
t.Fatalf("effective provider credential = %+v, want a resolved process-local env name", got)
|
||||
}
|
||||
t.Cleanup(func() { _ = os.Unsetenv(got.APIKeyEnv) })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestReloadConfigKeepsDatabaseOwnedSettings is archie-core-ju85. The SIGHUP
|
||||
// callback re-resolves the file document alone; without re-applying the
|
||||
// control plane over it, every database-owned setting reverts to its file
|
||||
// value until the process restarts, and the reload still logs success.
|
||||
func TestReloadConfigKeepsDatabaseOwnedSettings(t *testing.T) {
|
||||
b := newReloadBoot(t, &controlPlaneStub{values: databaseOwnedResources()})
|
||||
if err := b.loadRuntimeConfig(t.Context()); err != nil {
|
||||
t.Fatalf("loadRuntimeConfig: %v", err)
|
||||
}
|
||||
if err := b.applyWorkflowExecutionSettings(t.Context(), workflow.ExecutionSettings{
|
||||
MaxModelToolSteps: 99, MaxRuntime: time.Hour, MaxConsecutiveGateFailures: 5,
|
||||
}, 4); err != nil {
|
||||
t.Fatalf("applyWorkflowExecutionSettings: %v", err)
|
||||
}
|
||||
|
||||
if err := b.reloadConfig(t.Context(), &configuration.Document{Config: fileConfig()}); err != nil {
|
||||
t.Fatalf("reloadConfig: %v", err)
|
||||
}
|
||||
|
||||
got := b.cfgHolder.Get()
|
||||
for _, tt := range []struct {
|
||||
field string
|
||||
got any
|
||||
want any
|
||||
}{
|
||||
{"Providers", got.Providers["main"].BaseURL, "https://db.example.com"},
|
||||
{"Models", got.Models["builder"], "main/db-model"},
|
||||
{"Repos", got.Repos[0].Name, "from-database"},
|
||||
{"Chat", got.Chat.Operator, "database"},
|
||||
{"PollInterval", time.Duration(got.PollInterval), 2 * time.Minute},
|
||||
{"MaxRetries", got.MaxRetries, 7},
|
||||
{"PluginDir", got.PluginDir, "/db/plugins"},
|
||||
{"Containers", got.Containers.Image, "archie:from-database"},
|
||||
{"Budgets", got.Budgets.MaxSteps, 99},
|
||||
} {
|
||||
if tt.got != tt.want {
|
||||
t.Errorf("%s reverted to its file value after reload: got %v, want %v", tt.field, tt.got, tt.want)
|
||||
}
|
||||
}
|
||||
if got.BotUser != "widget" {
|
||||
t.Errorf("file-owned BotUser = %q, want the reloaded file value", got.BotUser)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReloadConfigFailsWhenControlPlaneUnreachable pins the direction of the
|
||||
// failure: the running config already holds the database's values, so a
|
||||
// control plane that cannot answer must abort the reload rather than publish
|
||||
// the file's values over them.
|
||||
func TestReloadConfigFailsWhenControlPlaneUnreachable(t *testing.T) {
|
||||
stub := &controlPlaneStub{values: databaseOwnedResources()}
|
||||
b := newReloadBoot(t, stub)
|
||||
if err := b.loadRuntimeConfig(t.Context()); err != nil {
|
||||
t.Fatalf("loadRuntimeConfig: %v", err)
|
||||
}
|
||||
|
||||
stub.queryErr = context.DeadlineExceeded
|
||||
err := b.reloadConfig(t.Context(), &configuration.Document{Config: fileConfig()})
|
||||
if err == nil {
|
||||
t.Fatal("reloadConfig with an unreachable control plane: expected an error")
|
||||
}
|
||||
if got := b.cfgHolder.Get(); got.Models["builder"] != "main/db-model" {
|
||||
t.Fatalf("running config was replaced on the error path: Models = %v", got.Models)
|
||||
}
|
||||
}
|
||||
@@ -1,273 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/daemon"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
// resourceWatchStub answers Query with one stored version per kind and Watch
|
||||
// with the documents queued for the watched kind. It is the store end of the
|
||||
// seam the runtime-resource watch meets a live update through, and it is the
|
||||
// store: delivering a document stores it, so the layering the apply runs
|
||||
// reads the update back from Query the way production does. A kind the map
|
||||
// does not carry is answered codes.NotFound, the state a skipped seed leaves
|
||||
// behind.
|
||||
type resourceWatchStub struct {
|
||||
values map[string]any
|
||||
// version is the stored version until a watch delivers an update, which
|
||||
// is the version the store then answers Query with -- the apply the
|
||||
// delivery triggers layers and reports the version the store now holds.
|
||||
version int64
|
||||
// storedVersion, when present, is the version Query answers a kind with.
|
||||
storedVersion map[string]int64
|
||||
// watch queues, per kind, the documents a live write delivers after the
|
||||
// stored version, one per stream: the first open delivers the first
|
||||
// document, the second open the second, and so on.
|
||||
watch map[string][]string
|
||||
// opens counts how often each kind's stream was opened, so queued
|
||||
// documents are delivered in order across the reconnects keepWatch runs.
|
||||
opens map[string]int
|
||||
}
|
||||
|
||||
func (s *resourceWatchStub) versionOf(kind string) int64 {
|
||||
if stored, ok := s.storedVersion[kind]; ok {
|
||||
return stored
|
||||
}
|
||||
return s.version
|
||||
}
|
||||
|
||||
func (*resourceWatchStub) Catalog(context.Context, *pb.CatalogRequest, ...grpc.CallOption) (*pb.CatalogResponse, error) {
|
||||
return &pb.CatalogResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *resourceWatchStub) Query(_ context.Context, request *pb.QueryRequest, _ ...grpc.CallOption) (*pb.QueryResponse, error) {
|
||||
value, ok := s.values[request.Kind]
|
||||
if !ok {
|
||||
return nil, status.Error(codes.NotFound, "resource not found")
|
||||
}
|
||||
encoded, err := json.Marshal(value)
|
||||
return &pb.QueryResponse{Resource: &pb.Resource{Kind: request.Kind, Version: s.versionOf(request.Kind), ValueJson: encoded}}, err
|
||||
}
|
||||
|
||||
func (s *resourceWatchStub) Watch(_ context.Context, request *pb.WatchRequest, _ ...grpc.CallOption) (grpc.ServerStreamingClient[pb.WatchResponse], error) {
|
||||
// One queued document per stream: a stream ends after the document it
|
||||
// carries, and the next one arrives on the reconnect -- the shape a store
|
||||
// whose writes are spaced apart produces, and the shape that keeps the
|
||||
// apply each delivery triggers reading the document back from Query
|
||||
// before the store has moved on to the next one.
|
||||
open := s.opens[request.Kind]
|
||||
s.opens[request.Kind] = open + 1
|
||||
if open >= len(s.watch[request.Kind]) {
|
||||
return &watchStreamStub{}, nil
|
||||
}
|
||||
document := s.watch[request.Kind][open]
|
||||
version := s.version + int64(open) + 1
|
||||
if version <= request.AfterVersion {
|
||||
return &watchStreamStub{}, nil
|
||||
}
|
||||
// The stub is the store: a document is stored when the stream delivers
|
||||
// it, so the apply that delivery triggers layers the document back from
|
||||
// Query.
|
||||
response := &pb.WatchResponse{Resource: &pb.Resource{
|
||||
Kind: request.Kind, Version: version, ValueJson: []byte(document),
|
||||
}}
|
||||
return &watchStreamStub{responses: []*pb.WatchResponse{response}, onDeliver: func() {
|
||||
s.values[request.Kind] = json.RawMessage(document)
|
||||
s.storedVersion[request.Kind] = version
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func (*resourceWatchStub) History(context.Context, *pb.HistoryRequest, ...grpc.CallOption) (*pb.HistoryResponse, error) {
|
||||
panic("unexpected History")
|
||||
}
|
||||
|
||||
func (*resourceWatchStub) Audit(context.Context, *pb.AuditRequest, ...grpc.CallOption) (*pb.AuditResponse, error) {
|
||||
return &pb.AuditResponse{}, nil
|
||||
}
|
||||
|
||||
func (*resourceWatchStub) Command(context.Context, *pb.CommandRequest, ...grpc.CallOption) (*pb.CommandResponse, error) {
|
||||
panic("unexpected Command")
|
||||
}
|
||||
|
||||
// newResourceWatchBoot builds a boot whose apply status lands in a recorder,
|
||||
// with the chat model runtime a provider or role update must rebuild.
|
||||
func newResourceWatchBoot(t *testing.T, stub *resourceWatchStub) (*boot, *applyStatusRecorder) {
|
||||
t.Helper()
|
||||
b, recorder := newLiveApplyBoot(t, fileConfig())
|
||||
b.controlPlane = controlplane.NewRPCClient(stub)
|
||||
b.secrets = secret.NewRegistry()
|
||||
b.chatModels = newChatModelManager(fileConfig().Models)
|
||||
b.setLLM(agentexec.NewRuntime(executionProviders(fileConfig())))
|
||||
return b, recorder
|
||||
}
|
||||
|
||||
// schedulingDocument renders a scheduling-policy document the layering reads
|
||||
// back, so the applied and refused updates in these tests cannot disagree on
|
||||
// what "the stored scheduling policy" is.
|
||||
func schedulingDocument(interval string) string {
|
||||
return `{"poll_interval": "` + interval + `", "max_retries": 7, "dispatch": {"trigger": "assignee"}}`
|
||||
}
|
||||
|
||||
// TestRuntimeResourceWatchReLayersTheStoredChangeAndRepublishes is the live
|
||||
// apply for the four kinds the daemon watches (archie-core-zfb0.1): a new
|
||||
// stored version of scheduling-policy re-runs the layering a reload runs and
|
||||
// republishes through config.Holder, so the change takes effect without a
|
||||
// restart, the apply status records the version that was applied, and every
|
||||
// other database-owned setting the layering read is still in the running
|
||||
// config.
|
||||
func TestRuntimeResourceWatchReLayersTheStoredChangeAndRepublishes(t *testing.T) {
|
||||
values := databaseOwnedResources()
|
||||
stub := &resourceWatchStub{values: values, version: 3, storedVersion: map[string]int64{}, opens: map[string]int{}, watch: map[string][]string{
|
||||
controlplane.SchedulingPolicyKind: {schedulingDocument("5m")},
|
||||
}}
|
||||
b, status := newResourceWatchBoot(t, stub)
|
||||
if err := b.loadRuntimeConfig(t.Context()); err != nil {
|
||||
t.Fatalf("loadRuntimeConfig: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
if err := b.startRuntimeResourceWatches(ctx, b.runtimeVersions); err != nil {
|
||||
t.Fatalf("startRuntimeResourceWatches: %v", err)
|
||||
}
|
||||
// One record for boot's layering, one for the watched update.
|
||||
records := status.awaitCount(t, controlplane.SchedulingPolicyKind, 2)
|
||||
|
||||
cfg := b.cfgHolder.Get()
|
||||
if got := time.Duration(cfg.PollInterval); got != 5*time.Minute {
|
||||
t.Errorf("running PollInterval = %s, want the watched update (5m)", got)
|
||||
}
|
||||
if got := cfg.Repos[0].Name; got != "from-database" {
|
||||
t.Errorf("running Repos[0] = %q, want the other kinds' last values to survive the re-layering", got)
|
||||
}
|
||||
last := records[len(records)-1]
|
||||
if last.AppliedVersion != stub.version+1 {
|
||||
t.Errorf("apply status version = %d, want the delivered version %d", last.AppliedVersion, stub.version+1)
|
||||
}
|
||||
if last.Error != "" {
|
||||
t.Errorf("apply status error = %q, want none for an applied update", last.Error)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRuntimeResourceWatchKeepsLastKnownGoodWhenTheUpdateIsRefused: an update
|
||||
// the layered document cannot run is refused before it is published, the
|
||||
// running config keeps the last version that was applied, and the refusal is
|
||||
// reported through apply status against the version still live.
|
||||
func TestRuntimeResourceWatchKeepsLastKnownGoodWhenTheUpdateIsRefused(t *testing.T) {
|
||||
stub := &resourceWatchStub{values: databaseOwnedResources(), version: 3, storedVersion: map[string]int64{}, opens: map[string]int{}, watch: map[string][]string{
|
||||
controlplane.SchedulingPolicyKind: {schedulingDocument("5m"), schedulingDocument("0s")},
|
||||
}}
|
||||
b, status := newResourceWatchBoot(t, stub)
|
||||
if err := b.loadRuntimeConfig(t.Context()); err != nil {
|
||||
t.Fatalf("loadRuntimeConfig: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
if err := b.startRuntimeResourceWatches(ctx, b.runtimeVersions); err != nil {
|
||||
t.Fatalf("startRuntimeResourceWatches: %v", err)
|
||||
}
|
||||
// One record for boot's layering, one for the applied update, one for the
|
||||
// refusal. The recorder keeps the version that is still live on a refusal,
|
||||
// so the third record carries the second update's version.
|
||||
records := status.awaitCount(t, controlplane.SchedulingPolicyKind, 3)
|
||||
|
||||
if got := time.Duration(b.cfgHolder.Get().PollInterval); got != 5*time.Minute {
|
||||
t.Errorf("running PollInterval = %s, want the last update that validated (5m)", got)
|
||||
}
|
||||
last := records[len(records)-1]
|
||||
if last.AppliedVersion != stub.version+1 {
|
||||
t.Errorf("apply status version = %d, want the version still live (%d)", last.AppliedVersion, stub.version+1)
|
||||
}
|
||||
if !strings.Contains(last.Error, "poll_interval must be positive") {
|
||||
t.Errorf("apply status error = %q, want it to carry the refusal", last.Error)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLiveModelRoleUpdateRebuildsTheChatModelRuntime: providers and model
|
||||
// role assignments also feed the gateway chat runtime, so an update to either
|
||||
// kind swaps the runtime (ai-sdk's Runtime caches the provider instances it
|
||||
// built) and re-derives the model list the chat surfaces offer.
|
||||
func TestLiveModelRoleUpdateRebuildsTheChatModelRuntime(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
kind string
|
||||
}{
|
||||
{"a provider settings update", controlplane.ProviderSettingsKind},
|
||||
{"a model role assignments update", controlplane.ModelRoleAssignmentsKind},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
values := databaseOwnedResources()
|
||||
values[controlplane.ModelRoleAssignmentsKind] = map[string]string{
|
||||
"builder": "main/db-model", "chat": "main/db-model",
|
||||
}
|
||||
stub := &resourceWatchStub{values: values, version: 3, storedVersion: map[string]int64{}, opens: map[string]int{}}
|
||||
b, _ := newResourceWatchBoot(t, stub)
|
||||
if err := b.loadRuntimeConfig(t.Context()); err != nil {
|
||||
t.Fatalf("loadRuntimeConfig: %v", err)
|
||||
}
|
||||
before := b.chatLLM()
|
||||
|
||||
b.applyRuntimeResourceUpdate(t.Context(), tt.kind, controlplane.AppliedResource{Version: 4})
|
||||
|
||||
if after := b.chatLLM(); after == before {
|
||||
t.Error("the chat runtime was not rebuilt; the next turn keeps the previous provider set")
|
||||
}
|
||||
if !slices.Contains(b.chatModels.Models(), "main/db-model") {
|
||||
t.Errorf("chat models = %v, want the new role assignment's reference", b.chatModels.Models())
|
||||
}
|
||||
if got := b.chatModels.ActiveModel(); got != "main/db-model" {
|
||||
t.Errorf("chat active model = %q, want the chat role's model after the update", got)
|
||||
}
|
||||
// The running config carries the update, not just the chat runtime.
|
||||
if got := b.cfgHolder.Get().Models["chat"]; got != "main/db-model" {
|
||||
t.Errorf("running chat role = %q, want the applied assignment", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLiveContainerRuntimePoliciesReLayerAndResizeTheDispatcher pins the
|
||||
// container kind's live seam (archie-core-zfb0.2) at the apply path: a stored
|
||||
// container-runtime-policies document re-layers into the running config the
|
||||
// pool reads per acquire, and the daemon resizes its running dispatcher from
|
||||
// the same publish rather than requiring a restart.
|
||||
func TestLiveContainerRuntimePoliciesReLayerAndResizeTheDispatcher(t *testing.T) {
|
||||
values := databaseOwnedResources()
|
||||
values[controlplane.ContainerRuntimePoliciesKind] = map[string]any{
|
||||
"image": "archie:live", "max_concurrency": 5, "pull_policy": "missing",
|
||||
}
|
||||
stub := &resourceWatchStub{values: values, version: 3, storedVersion: map[string]int64{}, opens: map[string]int{}}
|
||||
b, _ := newResourceWatchBoot(t, stub)
|
||||
if err := b.loadRuntimeConfig(t.Context()); err != nil {
|
||||
t.Fatalf("loadRuntimeConfig: %v", err)
|
||||
}
|
||||
// A running daemon, so the resize arm executes against a real dispatcher
|
||||
// rather than taking the boot-window nil guard.
|
||||
b.d = &daemon.Daemon{Cfg: b.cfgHolder, Log: b.log}
|
||||
|
||||
b.applyRuntimeResourceUpdate(t.Context(), controlplane.ContainerRuntimePoliciesKind, controlplane.AppliedResource{Version: 4})
|
||||
|
||||
got := b.cfgHolder.Get().Containers
|
||||
if got.MaxConcurrency != 5 {
|
||||
t.Errorf("running max_concurrency = %d, want the stored 5", got.MaxConcurrency)
|
||||
}
|
||||
if got.Image != "archie:live" {
|
||||
t.Errorf("running image = %q, want the stored archie:live", got.Image)
|
||||
}
|
||||
}
|
||||
@@ -1,440 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/applystatus"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
|
||||
// restartAdminToken is the administrative credential the State Store's
|
||||
// TaskGrants interceptor accepts. PutApplyStatus and ListApplyStatus are
|
||||
// administrative (docs/prds/control-plane-apply-status.md): a task-scoped
|
||||
// grant is denied by authorizesTaskScopedCall's deny-by-default arm, so the
|
||||
// harness that reads and writes apply status must dial as the administrator.
|
||||
const restartAdminToken = "eju6-admin-token"
|
||||
|
||||
// documentedStaleWindow is the window the operator-facing contract documents:
|
||||
// every process re-stamps its records every 30 seconds, and "a record is stale
|
||||
// once it is older than 90 seconds" (docs/prds/control-plane-apply-status.md,
|
||||
// "What is reported"). It is a fixture literal on purpose. Reading
|
||||
// applystatus.StaleAfter here would derive the aged row from the constant the
|
||||
// reader is supposed to honour, so the fixture would move with any mutation of
|
||||
// that constant and the reading below would agree with the reader by
|
||||
// construction -- a test that passes for a window measured in hours is a test
|
||||
// that never went stale at all.
|
||||
const documentedStaleWindow = 90 * time.Second
|
||||
|
||||
// restartEditedSettings is the change the dashboard writes. It differs from
|
||||
// fileConfig()'s [budgets] on all three fields, so a process that comes back on
|
||||
// any file value is detectably not on the stored one.
|
||||
var restartEditedSettings = workflow.ExecutionSettings{
|
||||
MaxModelToolSteps: 40, MaxRuntime: 10 * time.Minute, MaxConsecutiveGateFailures: 2, MaxTaskRuntime: 4 * time.Hour,
|
||||
}
|
||||
|
||||
// controlPlaneRestartFixture is a real State Store for the restart test: the
|
||||
// production control plane and apply-status surfaces registered on the real
|
||||
// gRPC service, behind TaskGrants' admin/task-grant interceptors, over a real
|
||||
// SQLite store. It is the composition state_store.go serves, not a stub.
|
||||
type controlPlaneRestartFixture struct {
|
||||
listener *bufconn.Listener
|
||||
admin *staterpc.Client
|
||||
}
|
||||
|
||||
// newControlPlaneRestartFixture opens the store, seeds it the way
|
||||
// archie-state-store does on a fresh database, serves the contract over
|
||||
// bufconn, and returns an administrative client for the dashboard and for
|
||||
// reading apply status back.
|
||||
func newControlPlaneRestartFixture(t *testing.T) *controlPlaneRestartFixture {
|
||||
t.Helper()
|
||||
local := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = local.Close() })
|
||||
|
||||
steps, err := stepVocabulary()
|
||||
if err != nil {
|
||||
t.Fatalf("build step vocabulary: %v", err)
|
||||
}
|
||||
control, err := controlplane.NewServer(local, steps)
|
||||
if err != nil {
|
||||
t.Fatalf("build control plane server: %v", err)
|
||||
}
|
||||
// The seed the State Store runs before it serves: every kind lands at
|
||||
// version 1 holding the file document's value. A kind the validator refused
|
||||
// would be absent, and the assertions below would then be testing a missing
|
||||
// resource rather than a restart, so this test names the two kinds it needs.
|
||||
versions, _, err := control.ImportConfig(t.Context(), fileConfig())
|
||||
if err != nil {
|
||||
t.Fatalf("seed control plane resources: %v", err)
|
||||
}
|
||||
for _, kind := range []string{controlplane.WorkflowExecutionSettingsKind, controlplane.PluginSettingsKind} {
|
||||
if versions[kind] != 1 {
|
||||
t.Fatalf("%s seeded at version %d, want 1", kind, versions[kind])
|
||||
}
|
||||
}
|
||||
|
||||
grants := &staterpc.TaskGrants{}
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
server := grpc.NewServer(
|
||||
grpc.ChainUnaryInterceptor(grants.UnaryInterceptor(restartAdminToken)),
|
||||
grpc.ChainStreamInterceptor(grants.StreamInterceptor(restartAdminToken)),
|
||||
)
|
||||
staterpc.RegisterServer(server, staterpc.Deps{
|
||||
ControlPlane: control, Tasks: local, ApplyStatus: local, Grants: grants,
|
||||
})
|
||||
go func() { _ = server.Serve(listener) }()
|
||||
t.Cleanup(func() { server.Stop(); _ = listener.Close() })
|
||||
|
||||
return &controlPlaneRestartFixture{
|
||||
listener: listener,
|
||||
admin: dialStateStore(t, listener, restartAdminToken),
|
||||
}
|
||||
}
|
||||
|
||||
// dial dials a fresh administrative connection, what a restarted process would
|
||||
// open to the State Store it does not own.
|
||||
func (f *controlPlaneRestartFixture) dial(t *testing.T) *staterpc.Client {
|
||||
t.Helper()
|
||||
return dialStateStore(t, f.listener, restartAdminToken)
|
||||
}
|
||||
|
||||
// dialStateStore is the production client wiring (staterpc.Dial, the only dial
|
||||
// path the daemon and dashboard use) against the non-loopback bridge address
|
||||
// every container-mode profile uses, with the dialer redirected to bufconn.
|
||||
func dialStateStore(t *testing.T, listener *bufconn.Listener, token string) *staterpc.Client {
|
||||
t.Helper()
|
||||
client, cleanup, err := staterpc.Dial("172.17.0.1:9090", token, grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) {
|
||||
return listener.DialContext(ctx)
|
||||
}))
|
||||
if err != nil {
|
||||
t.Fatalf("dial state store: %v", err)
|
||||
}
|
||||
t.Cleanup(cleanup)
|
||||
return client
|
||||
}
|
||||
|
||||
// startRestartProcess composes the consuming half of archied the way run()
|
||||
// composes it: boot.runtimeConfig layers the stored restart-required kinds over
|
||||
// the file document, and the watched execution settings are applied and
|
||||
// recorded from there. Apply status is reported through the State Store
|
||||
// contract by the process's own reporter.
|
||||
func startRestartProcess(ctx context.Context, t *testing.T, client *staterpc.Client) *boot {
|
||||
t.Helper()
|
||||
base := fileConfig()
|
||||
b := &boot{
|
||||
cfg: base,
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
processName: applystatus.Daemon,
|
||||
cfgHolder: config.NewHolder(base),
|
||||
controlPlane: controlplane.NewRPCClient(client.ControlPlane()),
|
||||
}
|
||||
b.applyStatus = applystatus.New(b.processName, client, b.log)
|
||||
if err := b.loadRuntimeConfig(ctx); err != nil {
|
||||
t.Fatalf("load runtime config: %v", err)
|
||||
}
|
||||
if err := b.startWorkflowExecutionSettings(ctx); err != nil {
|
||||
t.Fatalf("start workflow execution settings: %v", err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// TestRestartKeepsADatabaseOwnedSettingsChange is archie-core-eju6, the
|
||||
// end-to-end restart test docs/prds/runtime-control-plane.md ("First
|
||||
// implementation") lists as a deliverable. It drives settings changes through
|
||||
// the dashboard's own control-plane handler, reads one back from the audit
|
||||
// trail, restarts the process that consumes it, and asserts the restarted
|
||||
// process is running the stored values rather than the file's -- across both
|
||||
// halves of boot.runtimeConfig: the queried restart-required kinds and the
|
||||
// watched execution budgets (archie-core-ju85).
|
||||
//
|
||||
// The restart is a fresh boot composition dialing a fresh connection to the
|
||||
// State Store that holds the change. State Store persistence is what an OS
|
||||
// restart preserves; re-creating the consumer is what an OS restart does to
|
||||
// the consumer, so nothing in the property under test is substituted.
|
||||
func TestRestartKeepsADatabaseOwnedSettingsChange(t *testing.T) {
|
||||
fixture := newControlPlaneRestartFixture(t)
|
||||
dashboard := &webui.Server{ControlPlane: fixture.admin.ControlPlane(), ApplyStatus: fixture.admin}
|
||||
|
||||
// A process is already running on the seeded values. It is stopped before
|
||||
// the edit so the restart below -- not the live watch -- is what reads the
|
||||
// change back.
|
||||
firstCtx, stopFirst := context.WithCancel(t.Context())
|
||||
first := startRestartProcess(firstCtx, t, fixture.dial(t))
|
||||
stopFirst()
|
||||
if got := first.cfgHolder.Get().Budgets; got != budgetsFor(workflow.ExecutionSettings{MaxModelToolSteps: 1, MaxRuntime: time.Minute, MaxTaskRuntime: 4 * time.Hour}) {
|
||||
t.Fatalf("first process budgets = %+v, want the seeded file budgets", got)
|
||||
}
|
||||
if got := first.cfgHolder.Get().PluginDir; got != fileConfig().PluginDir {
|
||||
t.Fatalf("first process plugin dir = %q, want the file's", got)
|
||||
}
|
||||
|
||||
// 1. The dashboard writes the change. Its handler, not this test, supplies
|
||||
// the attribution: webAudit attributes to identity.SystemID.
|
||||
expectedVersion := int64(1)
|
||||
executionSettingsDocument := []byte(`{"max_model_tool_steps":40,"max_runtime_seconds":600,"max_consecutive_gate_failures":2,"max_task_runtime_seconds":14400}`)
|
||||
if version := dashboardReplace(t, dashboard, controlplane.WorkflowExecutionSettingsKind, executionSettingsDocument, expectedVersion); version != 2 {
|
||||
t.Fatalf("workflow execution settings after edit = version %d, want 2", version)
|
||||
}
|
||||
pluginDocument := []byte(`{"plugin_dir":"/db/plugins","module_dir":"/db/modules","secret_engine_dir":"/db/secrets","skills_dir":"/db/skills"}`)
|
||||
if version := dashboardReplace(t, dashboard, controlplane.PluginSettingsKind, pluginDocument, expectedVersion); version != 2 {
|
||||
t.Fatalf("plugin settings after edit = version %d, want 2", version)
|
||||
}
|
||||
|
||||
// 2. The change lands in the audit trail as an ordinary operator edit: the
|
||||
// newest revision names the dashboard and the System identity, and carries
|
||||
// the version it replaced.
|
||||
revisions := dashboardHistory(t, dashboard, controlplane.WorkflowExecutionSettingsKind)
|
||||
if len(revisions) != 2 {
|
||||
t.Fatalf("revisions = %d, want the seed and the edit", len(revisions))
|
||||
}
|
||||
edit := revisions[0]
|
||||
if edit.Version != 2 || edit.Actor != string(identity.SystemID) || edit.Source != "archie-ui" || edit.RequestID == "" {
|
||||
t.Fatalf("newest revision audit = %+v, want the dashboard's System-attributed edit at version 2", edit)
|
||||
}
|
||||
if revisions[1].Actor != "system:migration" || revisions[1].Version != 1 {
|
||||
t.Fatalf("older revision = %+v, want the migration seed it replaced", revisions[1])
|
||||
}
|
||||
// The value rides along, so a restore is an ordinary replace of it.
|
||||
if got := decodeExecutionSettingsRevision(t, edit.Value); got != restartEditedSettings {
|
||||
t.Fatalf("revision value = %+v, want the edited %+v", got, restartEditedSettings)
|
||||
}
|
||||
|
||||
// 3-4. Restart the consumer. It re-resolves the same file document and
|
||||
// must come back on the stored values for both the queried kind and the
|
||||
// watched budgets.
|
||||
restartCtx, stopRestart := context.WithCancel(t.Context())
|
||||
defer stopRestart()
|
||||
restarted := startRestartProcess(restartCtx, t, fixture.dial(t))
|
||||
|
||||
settings := restarted.executionSettings.Load()
|
||||
if settings == nil {
|
||||
t.Fatal("restarted process recorded no workflow execution settings")
|
||||
}
|
||||
if *settings != restartEditedSettings {
|
||||
t.Errorf("restarted settings = %+v, want the stored %+v", *settings, restartEditedSettings)
|
||||
}
|
||||
if got := restarted.cfgHolder.Get().Budgets; got != budgetsFor(restartEditedSettings) {
|
||||
t.Errorf("restarted budgets = %+v, want the stored %+v", got, budgetsFor(restartEditedSettings))
|
||||
}
|
||||
if got := restarted.cfgHolder.Get().PluginDir; got != "/db/plugins" {
|
||||
t.Errorf("restarted plugin dir = %q, want the stored /db/plugins, not the file's %q", got, fileConfig().PluginDir)
|
||||
}
|
||||
|
||||
// The SIGHUP reload re-resolves the file document alone. It runs the same
|
||||
// boot.runtimeConfig, so it must not revert either half to its file value
|
||||
// (archie-core-ju85).
|
||||
if err := restarted.reloadConfig(restartCtx, &configuration.Document{Config: fileConfig()}); err != nil {
|
||||
t.Fatalf("reload: %v", err)
|
||||
}
|
||||
if got := restarted.cfgHolder.Get().Budgets; got != budgetsFor(restartEditedSettings) {
|
||||
t.Errorf("budgets after reload = %+v, want the stored %+v re-applied", got, budgetsFor(restartEditedSettings))
|
||||
}
|
||||
if got := restarted.cfgHolder.Get().PluginDir; got != "/db/plugins" {
|
||||
t.Errorf("plugin dir after reload = %q, want the stored /db/plugins", got)
|
||||
}
|
||||
|
||||
// 5. The restarted process reports the version it applied, for both halves,
|
||||
// and a record that has stopped being re-stamped reads as not reporting.
|
||||
reported, err := fixture.admin.ListApplyStatus(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("list apply status: %v", err)
|
||||
}
|
||||
for _, kind := range []string{controlplane.WorkflowExecutionSettingsKind, controlplane.PluginSettingsKind} {
|
||||
record := applyStatusFor(t, reported, applystatus.Daemon, kind)
|
||||
if record.AppliedVersion != 2 {
|
||||
t.Errorf("%s apply status version = %d, want the applied 2", kind, record.AppliedVersion)
|
||||
}
|
||||
if record.Error != "" {
|
||||
t.Errorf("%s apply status error = %q, want none for an applied version", kind, record.Error)
|
||||
}
|
||||
}
|
||||
|
||||
statusView := dashboardApplyStatus(t, dashboard)
|
||||
live := applyStatusViewFor(t, statusView, applystatus.Daemon, controlplane.WorkflowExecutionSettingsKind)
|
||||
if live.State != "current" {
|
||||
t.Errorf("a record re-stamped at restart reads %q, want current", live.State)
|
||||
}
|
||||
|
||||
// One record per (process, kind), replaced in place: an old report for the
|
||||
// same key replaces the live one rather than sitting beside it.
|
||||
stale := time.Now().Add(-documentedStaleWindow - time.Second)
|
||||
if err := fixture.admin.PutApplyStatus(t.Context(), storecontract.ApplyStatus{
|
||||
Process: applystatus.Daemon, Kind: controlplane.WorkflowExecutionSettingsKind,
|
||||
AppliedVersion: 2, ReportedAt: stale,
|
||||
}); err != nil {
|
||||
t.Fatalf("put stale apply status: %v", err)
|
||||
}
|
||||
statusView = dashboardApplyStatus(t, dashboard)
|
||||
aged := applyStatusViewFor(t, statusView, applystatus.Daemon, controlplane.WorkflowExecutionSettingsKind)
|
||||
if aged.State != "unknown" {
|
||||
t.Errorf("a record older than %v reads %q, want unknown rather than current", documentedStaleWindow, aged.State)
|
||||
}
|
||||
if count := countApplyStatusViews(statusView, applystatus.Daemon, controlplane.WorkflowExecutionSettingsKind); count != 1 {
|
||||
t.Errorf("rows for (%s, %s) = %d, want the report replaced in place", applystatus.Daemon, controlplane.WorkflowExecutionSettingsKind, count)
|
||||
}
|
||||
|
||||
// The administrative credential is what admits the report: a task-scoped
|
||||
// grant, which the daemon issues to agent containers, is refused by both
|
||||
// apply-status RPCs.
|
||||
grant, err := fixture.admin.RegisterTaskGrant(t.Context(), 1, time.Hour)
|
||||
if err != nil {
|
||||
t.Fatalf("register task grant: %v", err)
|
||||
}
|
||||
taskScoped := dialStateStore(t, fixture.listener, grant)
|
||||
if _, err := taskScoped.ListApplyStatus(t.Context()); status.Code(err) != codes.PermissionDenied {
|
||||
t.Errorf("ListApplyStatus with a task-scoped grant = %v, want PermissionDenied", err)
|
||||
}
|
||||
if err := taskScoped.PutApplyStatus(t.Context(), storecontract.ApplyStatus{Process: applystatus.Daemon, Kind: controlplane.PluginSettingsKind, AppliedVersion: 9}); status.Code(err) != codes.PermissionDenied {
|
||||
t.Errorf("PutApplyStatus with a task-scoped grant = %v, want PermissionDenied", err)
|
||||
}
|
||||
}
|
||||
|
||||
type controlPlaneRevision struct {
|
||||
Version int64 `json:"version"`
|
||||
Value json.RawMessage `json:"value"`
|
||||
Actor string `json:"actor"`
|
||||
Source string `json:"source"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
type applyStatusRecord struct {
|
||||
Process string `json:"process"`
|
||||
Kind string `json:"kind"`
|
||||
AppliedVersion int64 `json:"applied_version"`
|
||||
Error string `json:"error"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
|
||||
// decodeExecutionSettingsRevision reads a revision's value in the same shape
|
||||
// the stored document uses, so the audit assertion compares values rather than
|
||||
// just versions.
|
||||
func decodeExecutionSettingsRevision(t *testing.T, value json.RawMessage) workflow.ExecutionSettings {
|
||||
t.Helper()
|
||||
var document struct {
|
||||
MaxModelToolSteps int `json:"max_model_tool_steps"`
|
||||
MaxRuntimeSeconds int64 `json:"max_runtime_seconds"`
|
||||
MaxConsecutiveGateFailures int `json:"max_consecutive_gate_failures"`
|
||||
MaxTaskRuntimeSeconds int64 `json:"max_task_runtime_seconds"`
|
||||
}
|
||||
if err := json.Unmarshal(value, &document); err != nil {
|
||||
t.Fatalf("decode revision value: %v (%s)", err, value)
|
||||
}
|
||||
return workflow.ExecutionSettings{
|
||||
MaxModelToolSteps: document.MaxModelToolSteps,
|
||||
MaxRuntime: time.Duration(document.MaxRuntimeSeconds) * time.Second,
|
||||
MaxConsecutiveGateFailures: document.MaxConsecutiveGateFailures,
|
||||
MaxTaskRuntime: time.Duration(document.MaxTaskRuntimeSeconds) * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
// dashboardReplace writes a resource the way the dashboard does -- through the
|
||||
// HTTP handler, which supplies the operator attribution the request body never
|
||||
// carries -- and returns the new version.
|
||||
func dashboardReplace(t *testing.T, server *webui.Server, kind string, value []byte, expectedVersion int64) int64 {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(map[string]any{"value": json.RawMessage(value), "expected_version": expectedVersion})
|
||||
if err != nil {
|
||||
t.Fatalf("encode %s request: %v", kind, err)
|
||||
}
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodPost,
|
||||
"/api/control-plane/resources/"+kind+"/commands/replace", bytes.NewReader(body))
|
||||
recorder := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("dashboard replace %s = %d, want 200: %s", kind, recorder.Code, recorder.Body.String())
|
||||
}
|
||||
var response struct {
|
||||
Resource struct {
|
||||
Version int64 `json:"version"`
|
||||
} `json:"resource"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
|
||||
t.Fatalf("decode %s replace response: %v (%s)", kind, err, recorder.Body.String())
|
||||
}
|
||||
return response.Resource.Version
|
||||
}
|
||||
|
||||
// dashboardHistory reads a resource's audit trail through the dashboard route,
|
||||
// so the edit observed is the one the UI would show.
|
||||
func dashboardHistory(t *testing.T, server *webui.Server, kind string) []controlPlaneRevision {
|
||||
t.Helper()
|
||||
var view struct {
|
||||
Revisions []controlPlaneRevision `json:"revisions"`
|
||||
}
|
||||
dashboardGET(t, server, "/api/control-plane/resources/"+kind+"/history", &view)
|
||||
return view.Revisions
|
||||
}
|
||||
|
||||
// dashboardApplyStatus reads the apply-status page the dashboard renders.
|
||||
func dashboardApplyStatus(t *testing.T, server *webui.Server) []applyStatusRecord {
|
||||
t.Helper()
|
||||
var view struct {
|
||||
Records []applyStatusRecord `json:"records"`
|
||||
}
|
||||
dashboardGET(t, server, "/api/control-plane/apply-status", &view)
|
||||
return view.Records
|
||||
}
|
||||
|
||||
func dashboardGET(t *testing.T, server *webui.Server, path string, target any) {
|
||||
t.Helper()
|
||||
recorder := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(recorder, httptest.NewRequestWithContext(t.Context(), http.MethodGet, path, nil))
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("GET %s = %d, want 200: %s", path, recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), target); err != nil {
|
||||
t.Fatalf("decode %s: %v (%s)", path, err, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func applyStatusFor(t *testing.T, statuses []storecontract.ApplyStatus, process, kind string) storecontract.ApplyStatus {
|
||||
t.Helper()
|
||||
for _, record := range statuses {
|
||||
if record.Process == process && record.Kind == kind {
|
||||
return record
|
||||
}
|
||||
}
|
||||
t.Fatalf("no apply status for (%s, %s) among %+v", process, kind, statuses)
|
||||
return storecontract.ApplyStatus{}
|
||||
}
|
||||
|
||||
func applyStatusViewFor(t *testing.T, records []applyStatusRecord, process, kind string) applyStatusRecord {
|
||||
t.Helper()
|
||||
for _, record := range records {
|
||||
if record.Process == process && record.Kind == kind {
|
||||
return record
|
||||
}
|
||||
}
|
||||
t.Fatalf("no apply-status row for (%s, %s) among %+v", process, kind, records)
|
||||
return applyStatusRecord{}
|
||||
}
|
||||
|
||||
func countApplyStatusViews(records []applyStatusRecord, process, kind string) int {
|
||||
count := 0
|
||||
for _, record := range records {
|
||||
if record.Process == process && record.Kind == kind {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
@@ -1,259 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
// staleDatabaseOwnedSettings are TOML fragments, each carrying one value a
|
||||
// control-plane resource is seeded from and replaces wholesale. They are the
|
||||
// values docs/prds/runtime-control-plane.md,
|
||||
// "Bootstrap, migration, and recovery" says must not block a process: "after
|
||||
// migration, settings in TOML are ignored and cannot block State Store
|
||||
// startup".
|
||||
var staleDatabaseOwnedSettings = []struct {
|
||||
name string
|
||||
body string
|
||||
}{
|
||||
{
|
||||
name: "provider base_url carrying userinfo",
|
||||
body: "[providers.openai]\nclass = \"openai\"\nbase_url = \"https://token@example.com/v1\"\n",
|
||||
},
|
||||
{
|
||||
name: "negative poll_interval",
|
||||
body: "poll_interval = \"-5s\"\n",
|
||||
},
|
||||
{
|
||||
name: "unrecognised dispatch.trigger",
|
||||
body: "[dispatch]\ntrigger = \"labels\"\n",
|
||||
},
|
||||
{
|
||||
name: "negative containers.volume_ttl",
|
||||
body: "[containers]\nvolume_ttl = \"-1m\"\n",
|
||||
},
|
||||
{
|
||||
name: "malformed repos test_glob",
|
||||
body: "[[repos]]\nowner = \"acme\"\nname = \"app\"\ntest_glob = \"[\"\n",
|
||||
},
|
||||
}
|
||||
|
||||
// TestLoadConfigAcceptsStaleDatabaseOwnedValues is the first of the two layers
|
||||
// archie-state-store boots through. loadConfig resolves the file and is where
|
||||
// the loader used to reject these values; it must not, because the setting
|
||||
// belongs to the control plane. The second layer is the boot itself, covered by
|
||||
// TestStateStoreBootsWithStaleDatabaseOwnedValues -- passing only this one is
|
||||
// not the item's claim.
|
||||
func TestLoadConfigAcceptsStaleDatabaseOwnedValues(t *testing.T) {
|
||||
for _, tt := range staleDatabaseOwnedSettings {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := t.TempDir() + "/config.toml"
|
||||
writeConfig(t, path, "bot_user = \"widget\"\n"+tt.body)
|
||||
|
||||
b := &boot{log: slog.New(slog.DiscardHandler)}
|
||||
if err := b.loadConfig(t.Context(), path, ""); err != nil {
|
||||
t.Fatalf("loadConfig: %v (a stale database-owned value must not fail boot)", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// staleBootGrace is how long one boot in
|
||||
// TestStateStoreBootsWithStaleDatabaseOwnedValues may run before the test cancels
|
||||
// it. A refusal arrives as an error before the cancel (first select); a boot
|
||||
// that serves returns only after the cancel (second select). The bound must be
|
||||
// long enough for a full boot -- now Postgres pool + migration, then SQLite and
|
||||
// the control-plane seed -- to finish, because cancelling mid-seed surfaces a
|
||||
// transaction error that reads as a refusal rather than as the interrupt it is.
|
||||
// 2s matches startupGrace, the sibling single-boot bound.
|
||||
//
|
||||
// staleShutdownGrace bounds the shutdown, and is deliberately not the 5s the
|
||||
// single-boot regression test uses: this table runs five boots back to back on a
|
||||
// host that may be busy, and the select returns the moment the process does, so
|
||||
// the bound costs nothing when shutdown is quick and only decides how long a
|
||||
// failure takes to report.
|
||||
const (
|
||||
staleBootGrace = 2 * time.Second
|
||||
staleShutdownGrace = 30 * time.Second
|
||||
)
|
||||
|
||||
// TestStateStoreBootsWithStaleDatabaseOwnedValues is the process-level half of
|
||||
// the item, and the layer that actually decides it: archie-state-store seeds
|
||||
// every control-plane resource from the same file config on a fresh database
|
||||
// (state_store.go, control.ImportConfig), and that seed is what runs the
|
||||
// resource's own validator. A seed that does not validate is skipped and
|
||||
// reported, not fatal -- the kind stays absent, the file's value is the one in
|
||||
// effect, and the operator's fix in config.toml is what clears it.
|
||||
func TestStateStoreBootsWithStaleDatabaseOwnedValues(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, tt := range staleDatabaseOwnedSettings {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.toml")
|
||||
body := fmt.Sprintf(
|
||||
"bot_user = 'archie'\ndatabase_url = %q\n%s[forge]\ntype = 'github'\nhost = 'https://github.example.com'\n",
|
||||
pgtest.URL(t), tt.body,
|
||||
)
|
||||
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Loopback, so no token is required. Cancellation is the assertion:
|
||||
// a boot that refuses the config returns before it, and one that
|
||||
// serves returns only when the context ends. Cancel first, then
|
||||
// assert -- racing startup against a wall clock is a coin flip.
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- RunStateStore(ctx, StateStoreOptions{Config: path, Listen: "127.0.0.1:0"})
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
t.Fatalf("RunStateStore returned before cancellation, want it to serve: %v", err)
|
||||
case <-time.After(staleBootGrace):
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case err := <-errCh:
|
||||
if err != nil && !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("RunStateStore returned %v, want nil or context.Canceled", err)
|
||||
}
|
||||
case <-time.After(staleShutdownGrace):
|
||||
t.Fatal("RunStateStore did not return within the shutdown grace after cancellation")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRuntimeConfigKeepsTheFileValueWhenAKindHasNoStoredResource is the other
|
||||
// end of a seed the control plane refused: the kind stays ABSENT rather than
|
||||
// being stored (ImportConfig skips it), and boot must then fall back to the
|
||||
// file document's value. Treating an absent kind as fatal is how a config the
|
||||
// file layer blesses left the daemon unbootable with a database-named error,
|
||||
// and left editing config.toml unable to fix it.
|
||||
func TestRuntimeConfigKeepsTheFileValueWhenAKindHasNoStoredResource(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
kind string
|
||||
check func(t *testing.T, cfg config.Config)
|
||||
}{
|
||||
{
|
||||
name: "repository policies",
|
||||
kind: controlplane.RepositoryPoliciesKind,
|
||||
check: func(t *testing.T, cfg config.Config) {
|
||||
t.Helper()
|
||||
if len(cfg.Repos) != 1 || cfg.Repos[0].Name != "from-file" {
|
||||
t.Errorf("Repos = %+v, want the file's from-file", cfg.Repos)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "scheduling policy",
|
||||
kind: controlplane.SchedulingPolicyKind,
|
||||
check: func(t *testing.T, cfg config.Config) {
|
||||
t.Helper()
|
||||
if cfg.PollInterval != config.Duration(time.Minute) {
|
||||
t.Errorf("PollInterval = %v, want the file's 1m", cfg.PollInterval)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "container runtime policies",
|
||||
kind: controlplane.ContainerRuntimePoliciesKind,
|
||||
check: func(t *testing.T, cfg config.Config) {
|
||||
t.Helper()
|
||||
if cfg.Containers.Image != "archie:from-file" {
|
||||
t.Errorf("Containers.Image = %q, want the file's archie:from-file", cfg.Containers.Image)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "providers",
|
||||
kind: controlplane.ProviderSettingsKind,
|
||||
check: func(t *testing.T, cfg config.Config) {
|
||||
t.Helper()
|
||||
if got := cfg.Providers["file"].Class; got != "openai" {
|
||||
t.Errorf("Providers[file].Class = %q, want the file's openai", got)
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
resources := databaseOwnedResources()
|
||||
delete(resources, tt.kind)
|
||||
b := newReloadBoot(t, &controlPlaneStub{values: resources})
|
||||
|
||||
if err := b.loadRuntimeConfig(t.Context()); err != nil {
|
||||
t.Fatalf("loadRuntimeConfig: %v (a kind with no stored value must leave the file's value in effect)", err)
|
||||
}
|
||||
tt.check(t, b.cfgHolder.Get())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDuplicateRepositoriesFailOnTheFilesOwnMessage is the end of the path the
|
||||
// fix-closure review found. A duplicate [[repos]] entry is refused by the
|
||||
// repository-policies validator, so the kind is never seeded and stays absent --
|
||||
// and boot must then fail on the FILE's copy of the value, naming the duplicate,
|
||||
// with the file as the fix. It used to fail on "control-plane resource not
|
||||
// found": a database-named error that editing config.toml could not clear.
|
||||
func TestDuplicateRepositoriesFailOnTheFilesOwnMessage(t *testing.T) {
|
||||
resources := databaseOwnedResources()
|
||||
delete(resources, controlplane.RepositoryPoliciesKind)
|
||||
b := newReloadBoot(t, &controlPlaneStub{values: resources})
|
||||
b.cfg.Repos = []config.Repo{{Owner: "acme", Name: "app"}, {Owner: "acme", Name: "app"}}
|
||||
|
||||
err := b.loadRuntimeConfig(t.Context())
|
||||
if err == nil {
|
||||
t.Fatal("loadRuntimeConfig accepted a duplicate repository list")
|
||||
}
|
||||
if !errors.Is(err, configuration.ErrInvalidInput) {
|
||||
t.Errorf("loadRuntimeConfig = %v, want it to wrap configuration.ErrInvalidInput", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "duplicates") {
|
||||
t.Errorf("loadRuntimeConfig = %v, want the duplicate named the way configuration.Validate names it", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
t.Errorf("loadRuntimeConfig = %v, want no absent-resource error: the file's value is the one in effect", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRuntimeConfigFailsClosedOnAnInvalidDatabaseValue is the other half of the
|
||||
// same change: the checks that no longer run at load run on the effective
|
||||
// document, at the one place database resources are layered in. A stored value
|
||||
// that will not validate must stop archied starting rather than be published as
|
||||
// the running configuration -- a state nothing can recover from in band.
|
||||
func TestRuntimeConfigFailsClosedOnAnInvalidDatabaseValue(t *testing.T) {
|
||||
resources := databaseOwnedResources()
|
||||
resources[controlplane.ProviderSettingsKind] = map[string]any{
|
||||
"main": map[string]any{"class": "openai", "base_url": "https://token@example.com/v1"},
|
||||
}
|
||||
b := newReloadBoot(t, &controlPlaneStub{values: resources})
|
||||
|
||||
err := b.loadRuntimeConfig(t.Context())
|
||||
if err == nil {
|
||||
t.Fatal("loadRuntimeConfig accepted a database value that does not validate")
|
||||
}
|
||||
if !errors.Is(err, configuration.ErrInvalidInput) {
|
||||
t.Errorf("loadRuntimeConfig = %v, want it to wrap configuration.ErrInvalidInput", err)
|
||||
}
|
||||
if got := b.cfgHolder.Get().Providers["main"].BaseURL; got == "https://token@example.com/v1" {
|
||||
t.Error("the invalid database value was published as the running configuration")
|
||||
}
|
||||
}
|
||||
@@ -1,189 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
|
||||
)
|
||||
|
||||
// outageStore is the State Store's resource half with a switch that makes every
|
||||
// read fail after taking stall to do it. It stands in for the outage the
|
||||
// reconnect exists for: the control plane takes the stream and then answers its
|
||||
// first read with mapError, so the client is handed a stream that ends carrying
|
||||
// no document -- while every reopen is accepted, because gRPC accepts before
|
||||
// the handler runs.
|
||||
//
|
||||
// The stall is the other shape that outage takes, and the shape a store that has
|
||||
// stopped answering actually has: it does not error at once, it stops reading
|
||||
// and the call times out. An attempt that ends that way delivered nothing and
|
||||
// lasted longer than the minimum retry interval, which is a failed attempt
|
||||
// whichever way the store failed it.
|
||||
type outageStore struct {
|
||||
*pgstore.TaskDB
|
||||
|
||||
mu sync.Mutex
|
||||
failing bool
|
||||
stall time.Duration
|
||||
}
|
||||
|
||||
// down starts the outage, which takes stall to surface.
|
||||
func (s *outageStore) down(stall time.Duration) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.failing, s.stall = true, stall
|
||||
}
|
||||
|
||||
func (s *outageStore) Resource(ctx context.Context, orgID, kind string) (storecontract.Resource, error) {
|
||||
s.mu.Lock()
|
||||
failing, stall := s.failing, s.stall
|
||||
s.mu.Unlock()
|
||||
if failing {
|
||||
time.Sleep(stall)
|
||||
return storecontract.Resource{}, errors.New("state store unreachable")
|
||||
}
|
||||
return s.TaskDB.Resource(ctx, orgID, kind)
|
||||
}
|
||||
|
||||
// TestWatchRetryGrowsWhileTheStateStoreIsDown is the outage this reconnect
|
||||
// exists for, end to end: a real controlplane.Server over bufconn, a real
|
||||
// controlplane.Client, a real store, and the store then stops answering -- in
|
||||
// each of the shapes it stops answering in, from the store that errors at once
|
||||
// to the one that takes as long to fail as the delay it would be charged.
|
||||
//
|
||||
// The server accepts every reopened stream and fails its first read, so the
|
||||
// client is handed an update for that failure that carries no version at all:
|
||||
// an attempt that ends this way delivered nothing, and the reconnect behind it
|
||||
// doubles the delay. That charge has to reach a store that fails slowly too.
|
||||
// The delay a slow failure is charged rests on the healthy window being derived
|
||||
// from the delay the attempt would otherwise be charged, not on the minimum: a
|
||||
// store that takes 300ms to time out outlived a window pinned at the 250ms
|
||||
// minimum on every attempt, so the delay never grew -- measured across 3s of
|
||||
// that shape, 1.7 watch RPCs a second with retry_in flat at 250ms, which is the
|
||||
// request loop this reconnect exists to avoid, reached by the likelier shape.
|
||||
//
|
||||
// The first retry is the minimum in every shape: the boot stream is a healthy
|
||||
// attempt, because the store answered it for longer than the window that
|
||||
// attempt would have been charged with before the outage began. The ladder's
|
||||
// top is reached by the delay alone and is pinned by
|
||||
// TestReconnectDelayFollowsAttemptHealth, which does not have to wait 30s for it.
|
||||
func TestWatchRetryGrowsWhileTheStateStoreIsDown(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
stall time.Duration
|
||||
want []time.Duration
|
||||
}{
|
||||
{
|
||||
name: "the store errors at once",
|
||||
want: []time.Duration{controlPlaneWatchRetryMin, 2 * controlPlaneWatchRetryMin, 4 * controlPlaneWatchRetryMin},
|
||||
},
|
||||
{
|
||||
name: "the store stalls before it times out",
|
||||
stall: 300 * time.Millisecond,
|
||||
want: []time.Duration{
|
||||
controlPlaneWatchRetryMin, 2 * controlPlaneWatchRetryMin,
|
||||
4 * controlPlaneWatchRetryMin, 8 * controlPlaneWatchRetryMin,
|
||||
},
|
||||
},
|
||||
{
|
||||
// The window an attempt is judged against is strictly wider than the
|
||||
// delay it would be charged with, and this is the shape that says so:
|
||||
// a failure that takes exactly that delay to surface is still a store
|
||||
// that did not answer the read.
|
||||
name: "the store fails as slowly as the delay it would be charged",
|
||||
stall: 2 * controlPlaneWatchRetryMin,
|
||||
want: []time.Duration{
|
||||
controlPlaneWatchRetryMin, 2 * controlPlaneWatchRetryMin,
|
||||
4 * controlPlaneWatchRetryMin, 8 * controlPlaneWatchRetryMin,
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
database := &outageStore{TaskDB: pgstore.Open(t)}
|
||||
defer database.Close()
|
||||
steps, err := workflowsteps.NewManager()
|
||||
if err != nil {
|
||||
t.Fatalf("build the workflow step vocabulary: %v", err)
|
||||
}
|
||||
server, err := controlplane.NewServer(database, steps)
|
||||
if err != nil {
|
||||
t.Fatalf("build the control plane: %v", err)
|
||||
}
|
||||
if _, err := server.ImportWorkflowExecutionSettings(t.Context(), bootedSettings); err != nil {
|
||||
t.Fatalf("seed the stored settings: %v", err)
|
||||
}
|
||||
|
||||
log, retries := newRetryLog()
|
||||
b, _ := newLiveApplyBoot(t, fileConfig())
|
||||
b.log = log
|
||||
b.controlPlane = controlplane.NewClient(dialControlPlane(t, server))
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
if err := b.startWorkflowExecutionSettings(ctx); err != nil {
|
||||
t.Fatalf("startWorkflowExecutionSettings: %v", err)
|
||||
}
|
||||
|
||||
// The store answers the boot stream for longer than the window that
|
||||
// attempt would be charged with, which is what makes it the healthy
|
||||
// attempt the first retry is not charged for.
|
||||
time.Sleep(controlPlaneWatchHealthyWindow(controlPlaneWatchRetryMin))
|
||||
database.down(tt.stall)
|
||||
|
||||
delays := awaitRetries(t, retries, len(tt.want))
|
||||
if got := delays[:len(tt.want)]; !slices.Equal(got, tt.want) {
|
||||
t.Errorf("reconnects waited %v, want %v: the delay is decided by the attempt that just ended, so the healthy boot attempt leaves the %v minimum behind and every attempt of the outage doubles the delay before it. A delay that never grows is this watch back at a request loop: pinned at %v by a healthy window fixed at the minimum, which a store that fails as slowly as this one outlives on every attempt, and pinned at %v by a reset on every reopen the store accepted, which charges each attempt of the outage from the minimum again",
|
||||
got, tt.want, controlPlaneWatchRetryMin, controlPlaneWatchRetryMin, 2*controlPlaneWatchRetryMin)
|
||||
}
|
||||
// Each logged retry is the wait the loop then took. A loop that logged
|
||||
// one delay and waited another would reopen sooner than it said it
|
||||
// would, and the attribute alone cannot show that.
|
||||
for i := 0; i < len(tt.want)-1; i++ {
|
||||
if gap := retries.gap(i); gap < tt.want[i] {
|
||||
t.Errorf("the retry logged as %v was followed by the next stream ending %v later, want at least that delay: the loop waits the delay it charged", tt.want[i], gap)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// dialControlPlane serves server over bufconn and returns the client
|
||||
// connection a watch dials it through. The transport is real: the stream's
|
||||
// context is the RPC's, and an unaccepted stream is not something a stub can
|
||||
// stand in for.
|
||||
func dialControlPlane(t *testing.T, server pb.ControlPlaneServiceServer) *grpc.ClientConn {
|
||||
t.Helper()
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
grpcServer := grpc.NewServer()
|
||||
pb.RegisterControlPlaneServiceServer(grpcServer, server)
|
||||
go func() { _ = grpcServer.Serve(listener) }()
|
||||
t.Cleanup(func() {
|
||||
grpcServer.Stop()
|
||||
_ = listener.Close()
|
||||
})
|
||||
conn, err := grpc.NewClient("passthrough:///control-plane",
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) {
|
||||
return listener.DialContext(ctx)
|
||||
}))
|
||||
if err != nil {
|
||||
t.Fatalf("dial the control plane: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
return conn
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,153 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/drain"
|
||||
)
|
||||
|
||||
const testInterval = 5 * time.Millisecond
|
||||
|
||||
// countShutdown returns a shutdown func plus a channel signalled on each call.
|
||||
func countShutdown(t *testing.T) (func(), *chan struct{}) {
|
||||
t.Helper()
|
||||
calls := make(chan struct{}, 1)
|
||||
return func() {
|
||||
select {
|
||||
case calls <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}, &calls
|
||||
}
|
||||
|
||||
func TestMonitorTriggersShutdownOnValidDecision(t *testing.T) {
|
||||
shutdown, calls := countShutdown(t)
|
||||
err := monitorDrainRequests(
|
||||
context.Background(),
|
||||
func() (drain.Decision, error) { return drain.DecisionValid, nil },
|
||||
shutdown,
|
||||
slog.New(slog.DiscardHandler),
|
||||
testInterval,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("monitorDrainRequests() error = %v, want nil", err)
|
||||
}
|
||||
select {
|
||||
case <-*calls:
|
||||
default:
|
||||
t.Fatal("shutdown was not invoked on a valid drain decision")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonitorDoesNotShutdownOnStaleDecision(t *testing.T) {
|
||||
shutdown, calls := countShutdown(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
// First poll returns stale; the monitor waits one interval. Cancel the
|
||||
// context before the next poll, then assert shutdown was never invoked and
|
||||
// the monitor returned the cancellation.
|
||||
go func() {
|
||||
time.Sleep(testInterval * 3)
|
||||
cancel()
|
||||
}()
|
||||
|
||||
err := monitorDrainRequests(
|
||||
ctx,
|
||||
func() (drain.Decision, error) { return drain.DecisionStale, nil },
|
||||
shutdown,
|
||||
slog.New(slog.DiscardHandler),
|
||||
testInterval,
|
||||
)
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("monitorDrainRequests() error = %v, want context.Canceled", err)
|
||||
}
|
||||
select {
|
||||
case <-*calls:
|
||||
t.Fatal("shutdown was invoked on a stale drain decision")
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonitorDoesNotShutdownOnNoMarker(t *testing.T) {
|
||||
shutdown, calls := countShutdown(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go func() {
|
||||
time.Sleep(testInterval * 3)
|
||||
cancel()
|
||||
}()
|
||||
|
||||
err := monitorDrainRequests(
|
||||
ctx,
|
||||
func() (drain.Decision, error) { return drain.DecisionNone, nil },
|
||||
shutdown,
|
||||
slog.New(slog.DiscardHandler),
|
||||
testInterval,
|
||||
)
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("monitorDrainRequests() error = %v, want context.Canceled", err)
|
||||
}
|
||||
select {
|
||||
case <-*calls:
|
||||
t.Fatal("shutdown was invoked with no drain marker")
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonitorDoesNotShutdownOnCheckError(t *testing.T) {
|
||||
shutdown, calls := countShutdown(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go func() {
|
||||
time.Sleep(testInterval * 3)
|
||||
cancel()
|
||||
}()
|
||||
|
||||
boom := errors.New("marker unreadable")
|
||||
err := monitorDrainRequests(
|
||||
ctx,
|
||||
func() (drain.Decision, error) { return drain.DecisionStale, boom },
|
||||
shutdown,
|
||||
slog.New(slog.DiscardHandler),
|
||||
testInterval,
|
||||
)
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("monitorDrainRequests() error = %v, want context.Canceled", err)
|
||||
}
|
||||
select {
|
||||
case <-*calls:
|
||||
t.Fatal("shutdown was invoked despite a check error")
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonitorShutdownAfterStaleThenValid(t *testing.T) {
|
||||
shutdown, calls := countShutdown(t)
|
||||
callsMade := 0
|
||||
err := monitorDrainRequests(
|
||||
context.Background(),
|
||||
func() (drain.Decision, error) {
|
||||
callsMade++
|
||||
if callsMade == 1 {
|
||||
return drain.DecisionStale, nil
|
||||
}
|
||||
return drain.DecisionValid, nil
|
||||
},
|
||||
shutdown,
|
||||
slog.New(slog.DiscardHandler),
|
||||
testInterval,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("monitorDrainRequests() error = %v, want nil", err)
|
||||
}
|
||||
select {
|
||||
case <-*calls:
|
||||
default:
|
||||
t.Fatal("shutdown was not invoked after a marker became valid")
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/module"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/playbook"
|
||||
)
|
||||
|
||||
type stubPlaybookLedger struct{}
|
||||
|
||||
func (stubPlaybookLedger) RecordPlaybookDispatch(context.Context, string, string, string, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (stubPlaybookLedger) DeletePlaybookDispatches(context.Context, string) error { return nil }
|
||||
|
||||
func loadBootPlaybooks(t *testing.T, document string) *playbook.Store {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "pb.yaml"), []byte(document), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b := &boot{cfg: config.Config{EDAPlaybookDir: dir}, modules: module.New()}
|
||||
if err := b.loadEDAPlaybooks(b.cfg, slog.New(slog.DiscardHandler)); err != nil {
|
||||
t.Fatalf("loadEDAPlaybooks: %v", err)
|
||||
}
|
||||
return b.playbooks
|
||||
}
|
||||
|
||||
const actionPlaybookDoc = `trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: module
|
||||
kind: log
|
||||
args:
|
||||
message: '"build started"'
|
||||
`
|
||||
|
||||
// An action playbook never runs without the dispatch ledger, and the
|
||||
// operator is told which ones are inert rather than finding out by silence.
|
||||
func TestPlaybookLedger(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
source any
|
||||
document string
|
||||
wantLedger bool
|
||||
wantWarn bool
|
||||
}{
|
||||
{name: "ledger wired", source: stubPlaybookLedger{}, document: actionPlaybookDoc, wantLedger: true},
|
||||
{name: "no ledger warns per action playbook", source: struct{}{}, document: actionPlaybookDoc, wantWarn: true},
|
||||
{name: "no ledger, workflow playbook only", source: struct{}{}, document: "trigger:\n kind: bug\nactions:\n - position: workflow\n workflow: tdd\n"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
got := playbookLedger(tt.source, loadBootPlaybooks(t, tt.document), slog.New(slog.NewTextHandler(&buf, nil)))
|
||||
if (got != nil) != tt.wantLedger {
|
||||
t.Fatalf("ledger = %v, want wired=%v", got, tt.wantLedger)
|
||||
}
|
||||
out := buf.String()
|
||||
warned := strings.Contains(out, "level=WARN") && strings.Contains(out, "pb.yaml") && strings.Contains(out, "will not run")
|
||||
if warned != tt.wantWarn {
|
||||
t.Fatalf("warning output = %q, want warned=%v", out, tt.wantWarn)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Autonomous execution has one production composition: managed task
|
||||
// containers over embedded or external NATS. These old switches must not
|
||||
// quietly restore a host or no-broker path in the composition root.
|
||||
func TestCompositionContainsNoAutonomousExecutionOptOut(t *testing.T) {
|
||||
for _, file := range []string{"bootstrap.go", "main.go"} {
|
||||
source, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, forbidden := range []string{"NATSModeOff", "Containers.Enabled"} {
|
||||
if strings.Contains(string(source), forbidden) {
|
||||
t.Errorf("%s contains removed autonomous execution switch %q", file, forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/domain/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/sdnotify"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
func TestGatewayServerOptsLoopbackIsInsecure(t *testing.T) {
|
||||
opts, loopback, err := gatewayServerOpts("127.0.0.1:8585", "")
|
||||
if err != nil {
|
||||
t.Fatalf("gatewayServerOpts(loopback, no token) error: %v", err)
|
||||
}
|
||||
if !loopback {
|
||||
t.Fatal("loopback listener should report loopback")
|
||||
}
|
||||
// Only the inbound size limit; a loopback listener installs no auth
|
||||
// interceptors (the count is the only handle on opaque ServerOptions).
|
||||
if len(opts) != 1 {
|
||||
t.Fatalf("loopback listener should install only the inbound size limit, got %d options", len(opts))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayServerOptsNonLoopbackRequiresToken(t *testing.T) {
|
||||
if _, _, err := gatewayServerOpts("0.0.0.0:8585", ""); err == nil {
|
||||
t.Fatal("non-loopback listener without a token should fail closed")
|
||||
}
|
||||
opts, loopback, err := gatewayServerOpts("0.0.0.0:8585", "secret")
|
||||
if err != nil {
|
||||
t.Fatalf("non-loopback listener with a token error: %v", err)
|
||||
}
|
||||
if loopback {
|
||||
t.Fatal("non-loopback listener should not report loopback")
|
||||
}
|
||||
if len(opts) != 3 {
|
||||
t.Fatalf("non-loopback listener should install three server options (inbound size limit plus unary and stream auth interceptors), got %d", len(opts))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayServerOptsMalformedListen(t *testing.T) {
|
||||
if _, _, err := gatewayServerOpts("not-an-address", ""); err == nil {
|
||||
t.Fatal("malformed listen address should error")
|
||||
}
|
||||
}
|
||||
|
||||
// stubGatewayContract satisfies messaging.ChatContract with zero values: the
|
||||
// serve test exercises the listener, the READY announcement and one read RPC,
|
||||
// not the chat runtime.
|
||||
type stubGatewayContract struct{}
|
||||
|
||||
func (stubGatewayContract) Snapshot(context.Context) (messaging.ChatSnapshot, error) {
|
||||
return messaging.ChatSnapshot{}, nil
|
||||
}
|
||||
|
||||
func (stubGatewayContract) GetSession(context.Context, string) (messaging.SessionContext, bool, error) {
|
||||
return messaging.SessionContext{}, false, nil
|
||||
}
|
||||
|
||||
func (stubGatewayContract) RecentMessages(context.Context, string, int) ([]messaging.Message, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (stubGatewayContract) RecentTurns(context.Context, string, int) ([]messaging.TurnRecord, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (stubGatewayContract) Route(context.Context, messaging.Inbound) (messaging.ChatReply, error) {
|
||||
return messaging.ChatReply{}, nil
|
||||
}
|
||||
|
||||
func (stubGatewayContract) Stream(context.Context, messaging.Inbound) (<-chan messaging.ChatEvent, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (stubGatewayContract) Cancel(context.Context, string) (messaging.ChatCancellation, error) {
|
||||
return messaging.ChatCancellation{}, nil
|
||||
}
|
||||
|
||||
func (stubGatewayContract) SetPersona(context.Context, string, string) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (stubGatewayContract) ApplyTaskAction(context.Context, string, int64, taskstate.Action, taskactions.ActionPayload) (messaging.TaskActionResult, error) {
|
||||
return messaging.TaskActionResult{}, nil
|
||||
}
|
||||
|
||||
func (stubGatewayContract) ApplyOperatorTaskAction(context.Context, taskactions.Actor, int64, taskstate.Action, taskactions.ActionPayload) (messaging.TaskActionResult, error) {
|
||||
return messaging.TaskActionResult{}, nil
|
||||
}
|
||||
|
||||
// TestGatewayServingAnnouncesReady: archie-gateway run as a Type=notify unit
|
||||
// must send READY=1 at the moment it declares itself serving, or systemd kills
|
||||
// a healthy process once TimeoutStartSec expires (archie-core-1174). The
|
||||
// announcement is judged against the same evidence archied's run loop uses:
|
||||
// the contract answers over the bound listener, so READY asserts a serving
|
||||
// process rather than a bound socket.
|
||||
func TestGatewayServingAnnouncesReady(t *testing.T) {
|
||||
listener := newNotifyListener(t)
|
||||
b := &boot{log: slog.New(slog.DiscardHandler)}
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
|
||||
ln, err := (&net.ListenConfig{}).Listen(ctx, "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
|
||||
serveCh := make(chan error, 1)
|
||||
go func() { serveCh <- b.serveGatewayListener(ctx, ln, true, stubGatewayContract{}, nil) }()
|
||||
|
||||
if !listener.waitForState(t, 5*time.Second, sdnotify.ReadyState) {
|
||||
t.Fatal("no READY=1 datagram within 5s of the Gateway serving")
|
||||
}
|
||||
|
||||
conn, err := grpc.NewClient("passthrough:///"+ln.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatalf("dial: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
if _, err := pb.NewChatServiceClient(conn).Snapshot(t.Context(), &pb.SnapshotRequest{}); err != nil {
|
||||
t.Fatalf("Snapshot over gRPC: %v", err)
|
||||
}
|
||||
|
||||
cancel()
|
||||
if err := <-serveCh; err != nil {
|
||||
t.Fatalf("serveGatewayListener returned: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// recordingGatewayContract captures the inbound a Stream call reached the
|
||||
// Gateway with, so a test can prove the request's payload survived the wire.
|
||||
type recordingGatewayContract struct {
|
||||
stubGatewayContract
|
||||
mu sync.Mutex
|
||||
last messaging.Inbound
|
||||
}
|
||||
|
||||
func (c *recordingGatewayContract) Stream(_ context.Context, in messaging.Inbound) (<-chan messaging.ChatEvent, error) {
|
||||
c.mu.Lock()
|
||||
c.last = in
|
||||
c.mu.Unlock()
|
||||
events := make(chan messaging.ChatEvent)
|
||||
close(events)
|
||||
return events, nil
|
||||
}
|
||||
|
||||
// TestGatewayAcceptsAnInboundAttachmentOverTheDefaultGRPCLimit: the inbound
|
||||
// request now carries a channel attachment's bytes, and gRPC's default receive
|
||||
// limit is 4 MB -- well under the messaging contract's ceiling. A maximal
|
||||
// attachment must reach the turn, not fail the RPC with ResourceExhausted.
|
||||
func TestGatewayAcceptsAnInboundAttachmentOverTheDefaultGRPCLimit(t *testing.T) {
|
||||
rec := &recordingGatewayContract{}
|
||||
ln, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
opts, _, err := gatewayServerOpts(ln.Addr().String(), "")
|
||||
if err != nil {
|
||||
t.Fatalf("gatewayServerOpts: %v", err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
serveCh := make(chan error, 1)
|
||||
go func() { serveCh <- serveGateway(ctx, ln, rec, nil, opts) }()
|
||||
defer func() {
|
||||
cancel()
|
||||
if err := <-serveCh; err != nil {
|
||||
t.Errorf("serveGateway: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
conn, err := grpc.NewClient("passthrough:///"+ln.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatalf("dial: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
raw := make([]byte, 5<<20) // larger than gRPC's 4 MB default receive limit
|
||||
stream, err := pb.NewChatServiceClient(conn).Stream(t.Context(), &pb.StreamRequest{
|
||||
Message: &pb.Message{Media: []*pb.Media{{Type: "image", MimeType: "image/jpeg", Data: raw}}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Stream with a %d-byte attachment: %v", len(raw), err)
|
||||
}
|
||||
if _, err := stream.Recv(); !errors.Is(err, io.EOF) {
|
||||
t.Fatalf("Recv after an empty stream: %v, want EOF", err)
|
||||
}
|
||||
|
||||
rec.mu.Lock()
|
||||
got := rec.last
|
||||
rec.mu.Unlock()
|
||||
if len(got.Media) != 1 {
|
||||
t.Fatalf("turn received %d attachments, want 1", len(got.Media))
|
||||
}
|
||||
if len(got.Media[0].Data) != len(raw) {
|
||||
t.Fatalf("turn received %d attachment bytes, want %d", len(got.Media[0].Data), len(raw))
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/health"
|
||||
)
|
||||
|
||||
// TestHealthSurfaceLivenessWaitsForBoot: the update watchdog restarts archied
|
||||
// and takes the first 200 as proof the new release came up. The listener
|
||||
// binds early so the port is not simply refused during boot, which means an
|
||||
// unconditional 200 would confirm a release that had not started yet.
|
||||
func TestHealthSurfaceLivenessWaitsForBoot(t *testing.T) {
|
||||
surface := &healthSurface{}
|
||||
handler := surface.handler()
|
||||
|
||||
for _, path := range []string{"/healthz", "/health"} {
|
||||
res := httptest.NewRecorder()
|
||||
handler.ServeHTTP(res, httptest.NewRequestWithContext(t.Context(), http.MethodGet, path, nil))
|
||||
if res.Code != http.StatusServiceUnavailable {
|
||||
t.Errorf("GET %s while booting = %d, want 503", path, res.Code)
|
||||
}
|
||||
}
|
||||
|
||||
surface.markServing()
|
||||
|
||||
for _, path := range []string{"/healthz", "/health"} {
|
||||
res := httptest.NewRecorder()
|
||||
handler.ServeHTTP(res, httptest.NewRequestWithContext(t.Context(), http.MethodGet, path, nil))
|
||||
if res.Code != http.StatusOK {
|
||||
t.Errorf("GET %s once serving = %d, want 200", path, res.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestHealthSurfaceDetailedReportsProbes: /health/detailed is the readiness
|
||||
// answer, and an unwired or degraded registry must never read as ready.
|
||||
func TestHealthSurfaceDetailedReportsProbes(t *testing.T) {
|
||||
var registry *health.Registry
|
||||
surface := &healthSurface{registry: func() *health.Registry { return registry }}
|
||||
surface.markServing()
|
||||
handler := surface.handler()
|
||||
|
||||
res := httptest.NewRecorder()
|
||||
handler.ServeHTTP(res, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health/detailed", nil))
|
||||
if res.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("detailed with no probes = %d, want 503", res.Code)
|
||||
}
|
||||
|
||||
registry = health.NewRegistry(failingProbe{})
|
||||
res = httptest.NewRecorder()
|
||||
handler.ServeHTTP(res, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health/detailed", nil))
|
||||
if res.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("detailed with a failing probe = %d, want 503", res.Code)
|
||||
}
|
||||
|
||||
registry = health.NewRegistry(passingProbe{})
|
||||
res = httptest.NewRecorder()
|
||||
handler.ServeHTTP(res, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health/detailed", nil))
|
||||
if res.Code != http.StatusOK {
|
||||
t.Fatalf("detailed with a passing probe = %d, want 200", res.Code)
|
||||
}
|
||||
}
|
||||
|
||||
type failingProbe struct{}
|
||||
|
||||
func (failingProbe) Name() string { return "test" }
|
||||
|
||||
func (failingProbe) Check(context.Context) health.Result {
|
||||
return health.Result{Status: health.StatusDegraded, Detail: "down"}
|
||||
}
|
||||
|
||||
type passingProbe struct{}
|
||||
|
||||
func (passingProbe) Name() string { return "test" }
|
||||
|
||||
func (passingProbe) Check(context.Context) health.Result {
|
||||
return health.Result{Status: health.StatusOK}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
package archied
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestResolveServiceListen pins the precedence: an explicit -listen wins, else
|
||||
// the configured address, and an address is never invented.
|
||||
//
|
||||
// The error cases are the ones that matter. net.Listen reads "" as "any free
|
||||
// port", so defaulting here would bind the service somewhere its clients do not
|
||||
// look and report success while doing it -- the exact failure this helper exists
|
||||
// to make impossible.
|
||||
func TestResolveServiceListen(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name, flagValue, configured, want string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "the flag wins over the configured address",
|
||||
flagValue: "127.0.0.1:9191", configured: "127.0.0.1:9090",
|
||||
want: "127.0.0.1:9191",
|
||||
},
|
||||
{
|
||||
name: "the configured address is used when no flag was passed",
|
||||
configured: "127.0.0.1:9191",
|
||||
want: "127.0.0.1:9191",
|
||||
},
|
||||
{
|
||||
name: "a whitespace flag is not an address",
|
||||
flagValue: " ", configured: "127.0.0.1:9191",
|
||||
want: "127.0.0.1:9191",
|
||||
},
|
||||
{
|
||||
name: "both empty is an error, never a silent ephemeral port",
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "whitespace on both sides is an error too",
|
||||
flagValue: " ", configured: "\t",
|
||||
wantErr: true,
|
||||
},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := resolveServiceListen("state", tt.flagValue, tt.configured)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("err = nil, want an error; got %q", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Fatalf("listen = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,98 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
)
|
||||
|
||||
func newSamplingTestRuntime(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = io.WriteString(w, `{"id":"chatcmpl-1","object":"chat.completion","created":1,"model":"gpt-5.6",`+
|
||||
`"choices":[{"index":0,"message":{"role":"assistant","content":"four"},"finish_reason":"stop"}],`+
|
||||
`"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`)
|
||||
}))
|
||||
t.Cleanup(api.Close)
|
||||
return api
|
||||
}
|
||||
|
||||
// TestMCPSamplingHandlerAnswersFromConfiguredModel proves a server-initiated
|
||||
// sampling request is answered by the daemon's own chat model and recorded on
|
||||
// /status like every other model call this process makes.
|
||||
func TestMCPSamplingHandlerAnswersFromConfiguredModel(t *testing.T) {
|
||||
api := newSamplingTestRuntime(t)
|
||||
|
||||
b := newBootstrap()
|
||||
b.setLLM(agentexec.NewRuntime(map[string]agentexec.Provider{
|
||||
"openai": {Class: "openai", BaseURL: api.URL},
|
||||
}))
|
||||
b.chatModels = newChatModelManager(map[string]string{"chat": "openai/gpt-5.6"})
|
||||
b.providerOutcomes = newProviderOutcomeRecorder()
|
||||
|
||||
result, err := b.mcpSamplingHandler()(t.Context(), mcp.SamplingRequest{
|
||||
Messages: []mcp.SamplingMessage{{
|
||||
Role: "user",
|
||||
Content: mcp.SamplingContent{Type: "text", Text: "2+2?"},
|
||||
}},
|
||||
MaxTokens: 16,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("sampling handler = %v, want a completion", err)
|
||||
}
|
||||
if result.Model != "openai/gpt-5.6" {
|
||||
t.Errorf("result.Model = %q, want the configured chat model", result.Model)
|
||||
}
|
||||
if result.Role != "assistant" || result.Content.Type != "text" || result.Content.Text != "four" {
|
||||
t.Errorf("result = %+v, want an assistant text completion", result)
|
||||
}
|
||||
outcome, attempted := b.providerOutcomes.LastChatModelOutcome()
|
||||
if !attempted || outcome.Model != "openai/gpt-5.6" || outcome.Err != "" {
|
||||
t.Errorf("recorded outcome = %+v (attempted %v), want the sampling call recorded as successful", outcome, attempted)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMCPSamplingHandlerRefusesCleanlyWithNoModel proves a daemon with no
|
||||
// usable model answers the request with an error instead of panicking or
|
||||
// dropping it: the server sees a failed request, not a dead session.
|
||||
func TestMCPSamplingHandlerRefusesCleanlyWithNoModel(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
wired bool
|
||||
want string
|
||||
}{
|
||||
{name: "no model runtime", wired: false, want: "no model runtime"},
|
||||
{name: "no chat model configured", wired: true, want: "no chat model"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
b := newBootstrap()
|
||||
if tc.wired {
|
||||
b.setLLM(agentexec.NewRuntime(map[string]agentexec.Provider{
|
||||
"openai": {Class: "openai"},
|
||||
}))
|
||||
}
|
||||
b.chatModels = newChatModelManager(nil)
|
||||
|
||||
_, err := b.mcpSamplingHandler()(t.Context(), mcp.SamplingRequest{
|
||||
Messages: []mcp.SamplingMessage{{
|
||||
Role: "user",
|
||||
Content: mcp.SamplingContent{Type: "text", Text: "hi"},
|
||||
}},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("sampling handler returned no error with no usable model")
|
||||
}
|
||||
if !strings.Contains(err.Error(), tc.want) {
|
||||
t.Errorf("error = %q, want it to mention %q", err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,250 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
|
||||
// catalogServer answers the model catalog read with a models.dev-shaped
|
||||
// document. It is the outside dependency the refresh loop actually meets:
|
||||
// modelcatalog.Load fetches this and caches what it read.
|
||||
func catalogServer(t *testing.T, document func() map[string]any) *httptest.Server {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(document())
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
// catalogProvider is one usable provider entry: an environment variable that
|
||||
// resolves (so modelcatalog keeps it) and the tool-callable models it offers.
|
||||
func catalogProvider(id, env string, models ...string) map[string]any {
|
||||
entries := make(map[string]any, len(models))
|
||||
for _, model := range models {
|
||||
entries[model] = map[string]any{
|
||||
"id": model, "name": strings.ToUpper(model), "tool_call": true,
|
||||
"limit": map[string]any{"context": 128000, "output": 16000},
|
||||
}
|
||||
}
|
||||
return map[string]any{
|
||||
"id": id, "name": strings.ToUpper(id), "npm": "@ai-sdk/openai-compatible",
|
||||
"api": "https://" + id + ".test/v1", "env": []string{env}, "models": entries,
|
||||
}
|
||||
}
|
||||
|
||||
// newCatalogBoot builds the smallest boot the refresh path runs against: the
|
||||
// control plane reads behind runtimeConfig, the secrets registry the catalog
|
||||
// resolves keys through, the chat runtime a refresh must reach, and a catalog
|
||||
// endpoint a test controls.
|
||||
func newCatalogBoot(t *testing.T, url string) *boot {
|
||||
t.Helper()
|
||||
b := newReloadBoot(t, &controlPlaneStub{values: databaseOwnedResources()})
|
||||
b.secrets = secret.NewRegistry()
|
||||
b.chatModels = newChatModelManager(fileConfig().Models)
|
||||
b.setLLM(agentexec.NewRuntime(executionProviders(fileConfig())))
|
||||
b.catalogURL = url
|
||||
b.catalogCachePath = filepath.Join(t.TempDir(), "models.json")
|
||||
if err := b.loadRuntimeConfig(t.Context()); err != nil {
|
||||
t.Fatalf("loadRuntimeConfig: %v", err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func awaitCatalog(t *testing.T, b *boot, ref string) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for !slices.Contains(b.chatModels.Models(), ref) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("chat models = %v, want %s to appear within the refresh interval", b.chatModels.Models(), ref)
|
||||
}
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefreshModelCatalogRepublishesEveryProjectionSite: a catalog read after
|
||||
// boot must reach everything derived from it -- the running config a workflow
|
||||
// stage resolves model limits from, the dashboard's published catalog view,
|
||||
// and the chat runtime's model list and details. A value that reaches the
|
||||
// boot struct alone parses and does nothing.
|
||||
func TestRefreshModelCatalogRepublishesEveryProjectionSite(t *testing.T) {
|
||||
srv := catalogServer(t, func() map[string]any {
|
||||
return map[string]any{"acme": catalogProvider("acme", "ACME_API_KEY", "acme-tool")}
|
||||
})
|
||||
t.Setenv("ACME_API_KEY", "resolved-by-the-secret-registry")
|
||||
b := newCatalogBoot(t, srv.URL)
|
||||
|
||||
if snapshot, _ := b.catalogState(); len(snapshot.Providers) != 0 {
|
||||
t.Fatalf("boot catalog = %+v, want the empty snapshot this test starts from", snapshot.Providers)
|
||||
}
|
||||
|
||||
if err := b.refreshModelCatalog(t.Context()); err != nil {
|
||||
t.Fatalf("refreshModelCatalog: %v", err)
|
||||
}
|
||||
|
||||
if got := b.cfgHolder.Get().ModelLimits["acme/acme-tool"]; got.ContextWindow != 128000 || got.MaxOutputTokens != 16000 {
|
||||
t.Errorf("running model limits = %+v, want the refreshed catalog's capacity", got)
|
||||
}
|
||||
if _, models := b.catalogState(); !slices.Contains(models, "acme/acme-tool") {
|
||||
t.Errorf("catalog models = %v, want the refreshed reference", models)
|
||||
}
|
||||
|
||||
view := webui.BuildConfigView(b.configViewInput(t.Context()))
|
||||
if len(view.Catalog) != 1 || view.Catalog[0].ID != "acme" {
|
||||
t.Fatalf("published catalog = %+v, want the refreshed provider", view.Catalog)
|
||||
}
|
||||
if !slices.Contains(view.Catalog[0].Models, "acme-tool") {
|
||||
t.Errorf("published catalog models = %v, want the refreshed model", view.Catalog[0].Models)
|
||||
}
|
||||
|
||||
if !slices.Contains(b.chatModels.Models(), "acme/acme-tool") {
|
||||
t.Errorf("chat models = %v, want the refreshed reference offered", b.chatModels.Models())
|
||||
}
|
||||
if _, ok := b.chatModels.ModelDetails("acme/acme-tool"); !ok {
|
||||
t.Error("chat model details missing the refreshed model")
|
||||
}
|
||||
if got := b.chatModels.ProviderDisplayName("acme"); got != "ACME" {
|
||||
t.Errorf("provider display name = %q, want the refreshed catalog's name", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestModelCatalogRefreshLoopPicksUpANewModelWhileTheDaemonRuns is the
|
||||
// without-a-restart proof: the process is already running on the catalog it
|
||||
// booted with, and a model that appears upstream afterwards is offered by the
|
||||
// next tick.
|
||||
func TestModelCatalogRefreshLoopPicksUpANewModelWhileTheDaemonRuns(t *testing.T) {
|
||||
var calls atomic.Int64
|
||||
srv := catalogServer(t, func() map[string]any {
|
||||
if calls.Add(1) == 1 {
|
||||
return map[string]any{"acme": catalogProvider("acme", "ACME_API_KEY", "acme-one")}
|
||||
}
|
||||
return map[string]any{"acme": catalogProvider("acme", "ACME_API_KEY", "acme-one", "acme-two")}
|
||||
})
|
||||
t.Setenv("ACME_API_KEY", "resolved-by-the-secret-registry")
|
||||
b := newCatalogBoot(t, srv.URL)
|
||||
if err := b.refreshModelCatalog(t.Context()); err != nil {
|
||||
t.Fatalf("initial refresh: %v", err)
|
||||
}
|
||||
if slices.Contains(b.chatModels.Models(), "acme/acme-two") {
|
||||
t.Fatal("the second model was offered before upstream published it")
|
||||
}
|
||||
|
||||
b.catalogRefreshInterval = 5 * time.Millisecond
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
b.startModelCatalogRefresh(ctx)
|
||||
|
||||
awaitCatalog(t, b, "acme/acme-two")
|
||||
if got := b.cfgHolder.Get().ModelLimits["acme/acme-two"]; got.ContextWindow != 128000 {
|
||||
t.Errorf("running model limits for the new model = %+v, want the refreshed capacity", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefreshModelCatalogKeepsTheLoadedCatalogWhenTheReadFails: the catalog
|
||||
// service having a bad minute must not blank the model list the process is
|
||||
// already running on. The failed read is reported; the snapshot stays.
|
||||
func TestRefreshModelCatalogKeepsTheLoadedCatalogWhenTheReadFails(t *testing.T) {
|
||||
srv := catalogServer(t, func() map[string]any {
|
||||
return map[string]any{"acme": catalogProvider("acme", "ACME_API_KEY", "acme-one")}
|
||||
})
|
||||
t.Setenv("ACME_API_KEY", "resolved-by-the-secret-registry")
|
||||
b := newCatalogBoot(t, srv.URL)
|
||||
if err := b.refreshModelCatalog(t.Context()); err != nil {
|
||||
t.Fatalf("refreshModelCatalog: %v", err)
|
||||
}
|
||||
|
||||
// The endpoint stops answering and the cache is gone, so the read has no
|
||||
// fallback left.
|
||||
srv.Close()
|
||||
if err := os.Remove(b.catalogCachePath); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
t.Fatalf("remove cache: %v", err)
|
||||
}
|
||||
if err := b.refreshModelCatalog(t.Context()); err == nil {
|
||||
t.Fatal("refreshModelCatalog error = nil, want the failed read reported")
|
||||
}
|
||||
|
||||
if _, models := b.catalogState(); !slices.Contains(models, "acme/acme-one") {
|
||||
t.Errorf("catalog models = %v, want the loaded catalog kept", models)
|
||||
}
|
||||
if got := b.cfgHolder.Get().ModelLimits["acme/acme-one"]; got.ContextWindow != 128000 {
|
||||
t.Errorf("running model limits = %+v, want the last-known-good catalog", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBootCatalogReachesTheRunningConfig is the projection-site check for the
|
||||
// boot half: the catalog boot read must be in the config the process runs on,
|
||||
// not only in the boot struct the chat runtime was built from. Otherwise the
|
||||
// first live update is the first snapshot to carry a catalog model limit.
|
||||
func TestBootCatalogReachesTheRunningConfig(t *testing.T) {
|
||||
srv := catalogServer(t, func() map[string]any {
|
||||
return map[string]any{"acme": catalogProvider("acme", "ACME_API_KEY", "acme-one")}
|
||||
})
|
||||
t.Setenv("ACME_API_KEY", "resolved-by-the-secret-registry")
|
||||
b := newCatalogBoot(t, srv.URL)
|
||||
|
||||
b.loadCatalog(t.Context(), filepath.Join(t.TempDir(), "config.toml"))
|
||||
|
||||
if got := b.cfgHolder.Get().ModelLimits["acme/acme-one"]; got.ContextWindow != 128000 {
|
||||
t.Errorf("running model limits = %+v, want the catalog boot loaded", got)
|
||||
}
|
||||
if _, models := b.catalogState(); !slices.Contains(models, "acme/acme-one") {
|
||||
t.Errorf("catalog models = %v, want the boot catalog", models)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatModelManagerReplacesItsCatalogRatherThanMerging: a refresh must
|
||||
// drop what the previous snapshot contributed. A manager that only merged
|
||||
// would keep offering a model the catalog no longer publishes, and would
|
||||
// describe a provider that no longer exists.
|
||||
func TestChatModelManagerReplacesItsCatalogRatherThanMerging(t *testing.T) {
|
||||
manager := newChatModelManager(map[string]string{"chat": "acme/one"})
|
||||
manager.SetModelCatalog(
|
||||
modelcatalog.Snapshot{Providers: []modelcatalog.Provider{
|
||||
{ID: "acme", Name: "Acme", Models: []modelcatalog.Model{{ID: "one"}, {ID: "two"}}},
|
||||
}},
|
||||
[]string{"acme/one", "acme/two"},
|
||||
)
|
||||
if !slices.Contains(manager.Models(), "acme/two") {
|
||||
t.Fatalf("chat models = %v, want the catalog's models offered", manager.Models())
|
||||
}
|
||||
if got := manager.ProviderDisplayName("acme"); got != "Acme" {
|
||||
t.Fatalf("provider display name = %q, want the catalog's name", got)
|
||||
}
|
||||
|
||||
manager.SetModelCatalog(
|
||||
modelcatalog.Snapshot{Providers: []modelcatalog.Provider{
|
||||
{ID: "acme", Name: "Acme", Models: []modelcatalog.Model{{ID: "one"}}},
|
||||
}},
|
||||
[]string{"acme/one"},
|
||||
)
|
||||
|
||||
if slices.Contains(manager.Models(), "acme/two") {
|
||||
t.Errorf("chat models = %v, want the withdrawn model dropped", manager.Models())
|
||||
}
|
||||
if _, ok := manager.ModelDetails("acme/two"); ok {
|
||||
t.Error("chat model details still carry the withdrawn model")
|
||||
}
|
||||
if got := manager.ProviderDisplayName("gone"); got != "" {
|
||||
t.Errorf("provider display name for an absent provider = %q, want empty", got)
|
||||
}
|
||||
if !slices.Contains(manager.Models(), "acme/one") {
|
||||
t.Errorf("chat models = %v, want the surviving model kept", manager.Models())
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog"
|
||||
)
|
||||
|
||||
func TestApplyModelCatalogNormalizesEveryExecutionScope(t *testing.T) {
|
||||
cfg := config.Config{
|
||||
Providers: map[string]config.Provider{
|
||||
"openai": {Class: "custom", APIKeyEnv: "CUSTOM_KEY"},
|
||||
},
|
||||
Identities: []config.IdentityConfig{
|
||||
{Name: "one", Providers: map[string]config.Provider{
|
||||
"identity-only": {Class: "openai-compatible"},
|
||||
}},
|
||||
},
|
||||
}
|
||||
snapshot := modelcatalog.Snapshot{Providers: []modelcatalog.Provider{
|
||||
{
|
||||
ID: "openai", Class: "openai", APIKeyEnv: "OPENAI_API_KEY",
|
||||
BaseURL: "https://api.openai.test/v1",
|
||||
Models: []modelcatalog.Model{{ID: "gpt-tool", ContextWindow: 128_000, MaxOutputTokens: 16_000}},
|
||||
},
|
||||
{
|
||||
ID: "anthropic", Class: "anthropic", APIKeyEnv: "ANTHROPIC_API_KEY",
|
||||
Models: []modelcatalog.Model{{ID: "claude-tool"}},
|
||||
},
|
||||
}}
|
||||
|
||||
models := applyModelCatalog(&cfg, snapshot)
|
||||
|
||||
if got := cfg.Providers["openai"]; got.Class != "custom" || got.APIKeyEnv != "CUSTOM_KEY" {
|
||||
t.Fatalf("explicit global provider was overwritten: %#v", got)
|
||||
}
|
||||
if _, ok := cfg.Providers["anthropic"]; !ok {
|
||||
t.Fatal("discovered provider missing from global execution config")
|
||||
}
|
||||
if _, ok := cfg.Identities[0].Providers["anthropic"]; !ok {
|
||||
t.Fatal("discovered provider missing from identity execution config")
|
||||
}
|
||||
if _, ok := cfg.Identities[0].Providers["identity-only"]; !ok {
|
||||
t.Fatal("explicit identity provider was removed")
|
||||
}
|
||||
wantModels := []string{"anthropic/claude-tool", "openai/gpt-tool"}
|
||||
if !reflect.DeepEqual(models, wantModels) {
|
||||
t.Fatalf("models = %v, want %v", models, wantModels)
|
||||
}
|
||||
if got := cfg.ModelLimits["openai/gpt-tool"]; got.ContextWindow != 128_000 || got.MaxOutputTokens != 16_000 {
|
||||
t.Fatalf("model limits = %+v, want catalog capacity", got)
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
|
||||
func TestCatalogViewListsEachAvailableProviderWithItsModels(t *testing.T) {
|
||||
snapshot := modelcatalog.Snapshot{Providers: []modelcatalog.Provider{
|
||||
{ID: "openai", Name: "OpenAI", Class: "openai", APIKeyEnv: "OPENAI_API_KEY", Models: []modelcatalog.Model{{ID: "gpt-b"}, {ID: "gpt-a"}}},
|
||||
{ID: "anthropic", Name: "Anthropic", Class: "anthropic", APIKeyEnv: "ANTHROPIC_API_KEY", BaseURL: "https://api.example", Models: []modelcatalog.Model{{ID: "claude"}}},
|
||||
}}
|
||||
want := []webui.CatalogProviderView{
|
||||
{ID: "anthropic", Name: "Anthropic", Class: "anthropic", APIKeyEnv: "ANTHROPIC_API_KEY", BaseURL: "https://api.example", Models: []string{"claude"}},
|
||||
{ID: "openai", Name: "OpenAI", Class: "openai", APIKeyEnv: "OPENAI_API_KEY", Models: []string{"gpt-a", "gpt-b"}},
|
||||
}
|
||||
if got := catalogView(snapshot); !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("catalogView =\n%#v\nwant\n%#v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalogViewOfAnEmptySnapshotIsEmptyNotNil(t *testing.T) {
|
||||
got := catalogView(modelcatalog.Snapshot{})
|
||||
if got == nil || len(got) != 0 {
|
||||
t.Fatalf("catalogView(empty) = %#v, want an empty slice", got)
|
||||
}
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/runtime"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
"github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
)
|
||||
|
||||
// capturedChatRequest is the JSON body the OpenAI-compatible provider sent for
|
||||
// the last call, which is where the max-token parameter name is chosen.
|
||||
type capturedChatRequest struct {
|
||||
mu sync.Mutex
|
||||
body map[string]any
|
||||
}
|
||||
|
||||
func (c *capturedChatRequest) get() map[string]any {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.body
|
||||
}
|
||||
|
||||
// newCapturingChatAPI answers every completion and records the wire body, so a
|
||||
// test can assert the parameter the provider actually emitted rather than an
|
||||
// option the composition root merely set.
|
||||
func newCapturingChatAPI(t *testing.T, capture *capturedChatRequest) *httptest.Server {
|
||||
t.Helper()
|
||||
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
capture.mu.Lock()
|
||||
capture.body = body
|
||||
capture.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = io.WriteString(w, `{"id":"chatcmpl-1","object":"chat.completion","created":1,"model":"test",`+
|
||||
`"choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],`+
|
||||
`"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`)
|
||||
}))
|
||||
t.Cleanup(api.Close)
|
||||
return api
|
||||
}
|
||||
|
||||
// assertWireBound asserts the max-token parameter the provider emitted: absent
|
||||
// entirely for a reasoning model (its only accepted form with this ai-sdk
|
||||
// release), present with the caller's bound for a classic one.
|
||||
func assertWireBound(t *testing.T, capture *capturedChatRequest, wantBound bool, wantValue int) {
|
||||
t.Helper()
|
||||
bound, present := capture.get()["max_tokens"]
|
||||
if present != wantBound {
|
||||
t.Fatalf("request body max_tokens present = %v (value %v), want %v; body = %v", present, bound, wantBound, capture.get())
|
||||
}
|
||||
if present && bound != float64(wantValue) {
|
||||
t.Fatalf("request body max_tokens = %v, want %d; body = %v", bound, wantValue, capture.get())
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatTurnParameterNameFollowsModelClass proves the chat turn path reaches
|
||||
// the provider without a max-token bound for a reasoning-class model, while a
|
||||
// classic model still carries one. The bound itself is unchanged; only the
|
||||
// parameter the chat-completions provider would serialise it into differs, and
|
||||
// reasoning models reject `max_tokens` with HTTP 400.
|
||||
func TestChatTurnParameterNameFollowsModelClass(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
reasoning bool
|
||||
wantBound bool
|
||||
modelRef string
|
||||
maxOutput int
|
||||
wantValue int
|
||||
}{
|
||||
{name: "reasoning model", reasoning: true, wantBound: false, modelRef: "openai/gpt-5.4", maxOutput: 4096},
|
||||
{name: "classic model", reasoning: false, wantBound: true, modelRef: "openai/gpt-4o", maxOutput: 4096, wantValue: 4096},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
capture := &capturedChatRequest{}
|
||||
api := newCapturingChatAPI(t, capture)
|
||||
llm := agentexec.NewRuntime(map[string]agentexec.Provider{
|
||||
"openai": {Class: "openai", BaseURL: api.URL},
|
||||
})
|
||||
model := newChatTurnModel(func() *runtime.Runtime { return llm }, tools.NewRegistry(), 1, func() agentexec.ToolLimits { return agentexec.ToolLimits{} }, nil)
|
||||
|
||||
prepared, err := model.Prepare(t.Context(), gateway.TurnPrepareContext{
|
||||
Model: tc.modelRef, Reasoning: tc.reasoning,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Prepare() error = %v", err)
|
||||
}
|
||||
_, err = prepared.Generate(t.Context(), gateway.TurnModelRequest{
|
||||
Messages: []gateway.CompressedMessage{{Role: "user", Content: "hi"}},
|
||||
MaxOutputTokens: tc.maxOutput,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Generate() error = %v", err)
|
||||
}
|
||||
|
||||
assertWireBound(t, capture, tc.wantBound, tc.wantValue)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestMCPSamplingParameterNameFollowsModelClass proves the second place the
|
||||
// process sets a max-token bound -- server-requested sampling, which also
|
||||
// applies a default when the request is silent -- preserves it for a classic
|
||||
// model and drops it entirely for a reasoning one.
|
||||
func TestMCPSamplingParameterNameFollowsModelClass(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
modelRef string
|
||||
model modelcatalog.Model
|
||||
wantBound bool
|
||||
wantValue int
|
||||
}{
|
||||
{
|
||||
name: "reasoning model",
|
||||
modelRef: "openai/gpt-5.4",
|
||||
model: modelcatalog.Model{ID: "gpt-5.4", Reasoning: true, MaxOutputTokens: 128000},
|
||||
},
|
||||
{
|
||||
name: "classic model",
|
||||
modelRef: "openai/gpt-4o",
|
||||
model: modelcatalog.Model{ID: "gpt-4o", MaxOutputTokens: 128000},
|
||||
wantBound: true,
|
||||
wantValue: agentexec.DefaultSamplingMaxTokens,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
capture := &capturedChatRequest{}
|
||||
api := newCapturingChatAPI(t, capture)
|
||||
b := newBootstrap()
|
||||
b.setLLM(agentexec.NewRuntime(map[string]agentexec.Provider{
|
||||
"openai": {Class: "openai", BaseURL: api.URL},
|
||||
}))
|
||||
b.chatModels = newChatModelManager(map[string]string{"chat": tc.modelRef})
|
||||
b.chatModels.SetModelCatalog(modelcatalog.Snapshot{
|
||||
Providers: []modelcatalog.Provider{{ID: "openai", Models: []modelcatalog.Model{tc.model}}},
|
||||
}, []string{tc.modelRef})
|
||||
b.providerOutcomes = newProviderOutcomeRecorder()
|
||||
|
||||
_, err := b.mcpSamplingHandler()(t.Context(), mcp.SamplingRequest{
|
||||
Messages: []mcp.SamplingMessage{{Role: "user", Content: mcp.SamplingContent{Type: "text", Text: "hi"}}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("sampling handler error = %v", err)
|
||||
}
|
||||
|
||||
assertWireBound(t, capture, tc.wantBound, tc.wantValue)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEmbeddedNATSEndpointRoundTripIsPrivateAndAtomic(t *testing.T) {
|
||||
stateDir := t.TempDir()
|
||||
if err := writeEmbeddedNATSEndpoint(stateDir, "nats://127.0.0.1:4222", "secret"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := readEmbeddedNATSEndpoint(stateDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.URL != "nats://127.0.0.1:4222" || got.Token != "secret" {
|
||||
t.Fatalf("endpoint = %+v", got)
|
||||
}
|
||||
if want := filepath.Join(stateDir, "nats", "endpoint.json"); embeddedNATSEndpointPath(stateDir) != want {
|
||||
t.Fatalf("endpoint path = %q, want %q", embeddedNATSEndpointPath(stateDir), want)
|
||||
}
|
||||
info, err := os.Stat(embeddedNATSEndpointPath(stateDir))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("endpoint permissions = %o, want 600", info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
@@ -1,155 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"context"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storepkg"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
)
|
||||
|
||||
// contributedLayer ships one workflow definition file's portable YAML.
|
||||
func contributedLayer(t *testing.T, path, yaml string) []byte {
|
||||
t.Helper()
|
||||
var raw bytes.Buffer
|
||||
writer := tar.NewWriter(&raw)
|
||||
if err := writer.WriteHeader(&tar.Header{Typeflag: tar.TypeReg, Name: path, Size: int64(len(yaml))}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := writer.Write([]byte(yaml)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return raw.Bytes()
|
||||
}
|
||||
|
||||
func packageDescriptor() storepkg.Descriptor {
|
||||
return storepkg.Descriptor{
|
||||
APIVersion: storepkg.APIVersion, DisplayName: "Review pack", Version: "1",
|
||||
Contributes: storepkg.Contributions{Workflows: []string{"workflows/review.yaml"}},
|
||||
Files: []storepkg.File{{Path: "workflows/review.yaml", Mode: 0o644}},
|
||||
}
|
||||
}
|
||||
|
||||
// TestPackageContributionsLiveRoundTrip drives the State Store's own
|
||||
// composition — the projections stateStoreDeps wires, the install and remove
|
||||
// RPCs the dashboard calls, and the workflow-definitions resource the daemon
|
||||
// reads per dispatch — over one real gRPC connection: installing a package
|
||||
// makes its workflow a usable org resource, and removing it stops being
|
||||
// usable, both without restarting anything.
|
||||
func TestPackageContributionsLiveRoundTrip(t *testing.T) {
|
||||
db := pgstore.Open(t)
|
||||
projections, err := newPackageProjections(db.Pool)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const yaml = "id: review\nsteps:\n - type: bootstrap.apply\n"
|
||||
service := storepkg.Service{
|
||||
Registry: packageLayerRegistry{descriptor: packageDescriptor(), layer: contributedLayer(t, "workflows/review.yaml", yaml)},
|
||||
Store: postgres.NewInstalledPackages(db.Pool),
|
||||
Projections: projections,
|
||||
}
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
server := grpc.NewServer()
|
||||
staterpc.RegisterServer(server, staterpc.Deps{Packages: service})
|
||||
go func() { _ = server.Serve(listener) }()
|
||||
t.Cleanup(func() { server.Stop(); _ = listener.Close() })
|
||||
conn, err := grpc.NewClient("passthrough:///state",
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) }))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
client := staterpc.NewClient(conn)
|
||||
const digest = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||
|
||||
if _, err := client.InstallPackage(t.Context(), "org-a", "review", "localhost:5000/review", digest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The contribution is usable: the org resource the daemon's
|
||||
// WorkflowDefinitions client reads carries it now, no restart involved.
|
||||
resource, err := postgres.NewResources(db.Pool).Resource(t.Context(), "org-a", controlplane.WorkflowDefinitionsKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
collection, err := workflow.DecodeDefinitionCollection(resource.Value, workflow.BuiltinStepRegistry())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := collection.DefinitionByID("review"); !ok {
|
||||
t.Fatal("installed package's workflow is not an org workflow after install")
|
||||
}
|
||||
if err := client.RemoveInstalled(t.Context(), "org-a", "review"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resource, err = postgres.NewResources(db.Pool).Resource(t.Context(), "org-a", controlplane.WorkflowDefinitionsKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
collection, err = workflow.DecodeDefinitionCollection(resource.Value, workflow.BuiltinStepRegistry())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := collection.DefinitionByID("review"); ok {
|
||||
t.Fatal("removed package's workflow still dispatches: the org resource kept it")
|
||||
}
|
||||
if entries, err := postgres.NewPackageContributions(db.Pool).Entries(t.Context(), "org-a", "review"); err != nil || len(entries) != 0 {
|
||||
t.Fatalf("contributions ledger after removal = %#v, %v", entries, err)
|
||||
}
|
||||
}
|
||||
|
||||
type packageLayerRegistry struct {
|
||||
descriptor storepkg.Descriptor
|
||||
layer []byte
|
||||
}
|
||||
|
||||
func (r packageLayerRegistry) Fetch(context.Context, string, string) (storepkg.Descriptor, []byte, error) {
|
||||
return r.descriptor, r.layer, nil
|
||||
}
|
||||
|
||||
// TestStateStoreDepsWiresPackageProjections pins the wiring the live round
|
||||
// trip drives: stateStoreDeps builds projections on the State Store's pool and
|
||||
// carries them into the packages service it composes.
|
||||
func TestStateStoreDepsWiresPackageProjections(t *testing.T) {
|
||||
file := "state_store.go"
|
||||
fset := token.NewFileSet()
|
||||
parsed, err := parser.ParseFile(fset, file, nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var calls []string
|
||||
ast.Inspect(parsed, func(node ast.Node) bool {
|
||||
if call, ok := node.(*ast.CallExpr); ok {
|
||||
if fn, ok := call.Fun.(*ast.Ident); ok {
|
||||
calls = append(calls, fn.Name)
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
found := false
|
||||
for _, call := range calls {
|
||||
if call == "newPackageProjections" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("stateStoreDeps (%s body) wires no package projections", file)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package archied
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestParseListenAddrPreservesEphemeralPort(t *testing.T) {
|
||||
host, port := parseListenAddr("127.0.0.1:0", "0.0.0.0", 8644)
|
||||
if host != "127.0.0.1" || port != 0 {
|
||||
t.Fatalf("parseListenAddr() = (%q, %d), want (%q, %d)", host, port, "127.0.0.1", 0)
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
// TestMain runs the archied test binary against a throwaway PostgreSQL 18
|
||||
// container, mirroring internal/infrastructure/postgres. The State Store's
|
||||
// openStateStore fails closed without a working database_url, so the tests
|
||||
// that exercise it (e.g. TestStateStoreDataSurvivesRestart) need a real pool.
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
@@ -1,297 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/module"
|
||||
"github.com/samcharles93/archie-core/internal/plugin"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
// docs/prds/plugin-settings-live.md: a plugin or secret-engine file dropped
|
||||
// into the running configuration's directory loads without a restart, an
|
||||
// edited file replaces what runs, and a removed file keeps running with the
|
||||
// removal reported through apply status until the process restarts.
|
||||
|
||||
const reconcilerPluginSource = `package main
|
||||
|
||||
import "github.com/samcharles93/archie-core/internal/plugin"
|
||||
|
||||
var Plugin = plugin._Plugin{
|
||||
WName: func() string { return "hello" },
|
||||
WVersion: func() string { return "1.0.0" },
|
||||
}
|
||||
`
|
||||
|
||||
const reconcilerSecretSource = `package main
|
||||
|
||||
import "github.com/samcharles93/archie-core/internal/secret"
|
||||
|
||||
var Engine = secret._Engine{
|
||||
WName: func() string { return "hello" },
|
||||
WVersion: func() string { return "1.0.0" },
|
||||
WResolve: func(key string) (string, error) { return "one:" + key, nil },
|
||||
}
|
||||
`
|
||||
|
||||
const reconcilerEditedSecretSource = `package main
|
||||
|
||||
import "github.com/samcharles93/archie-core/internal/secret"
|
||||
|
||||
var Engine = secret._Engine{
|
||||
WName: func() string { return "hello" },
|
||||
WVersion: func() string { return "2.0.0" },
|
||||
WResolve: func(key string) (string, error) { return "two:" + key, nil },
|
||||
}
|
||||
`
|
||||
|
||||
// reconcilerHarness is one running directory set: a started plugin host, a
|
||||
// fresh secret registry, an empty module registry, and the config that names
|
||||
// the two directories a test writes into.
|
||||
type reconcilerHarness struct {
|
||||
root *plugin.Host
|
||||
secrets *secret.Registry
|
||||
cfg config.Config
|
||||
plugins string
|
||||
secretsD string
|
||||
mods *module.ModuleRegistry
|
||||
}
|
||||
|
||||
func newReconcilerHarness(t *testing.T) *reconcilerHarness {
|
||||
t.Helper()
|
||||
h := &reconcilerHarness{
|
||||
root: plugin.NewHost(),
|
||||
secrets: secret.NewRegistry(),
|
||||
mods: module.New(),
|
||||
plugins: t.TempDir(),
|
||||
secretsD: t.TempDir(),
|
||||
}
|
||||
if err := h.root.Start(t.Context()); err != nil {
|
||||
t.Fatalf("start host: %v", err)
|
||||
}
|
||||
h.cfg = config.Config{PluginDir: h.plugins, SecretEngineDir: h.secretsD}
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *reconcilerHarness) reconciler() *pluginReconciler {
|
||||
return newPluginReconciler(slog.New(slog.DiscardHandler), pluginReconcileTargets{
|
||||
host: h.root,
|
||||
secrets: h.secrets,
|
||||
modules: h.mods,
|
||||
dirs: func() config.Config { return h.cfg },
|
||||
})
|
||||
}
|
||||
|
||||
func writeReconcilerFile(t *testing.T, path, source string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(path, []byte(source), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPluginReconcilerLoadsADroppedPluginAndSecretEngine(t *testing.T) {
|
||||
h := newReconcilerHarness(t)
|
||||
r := h.reconciler()
|
||||
// Boot loaded the (empty) directories; seed is what the daemon does after
|
||||
// its own boot load so the first tick does not re-load the boot set.
|
||||
r.seed()
|
||||
|
||||
writeReconcilerFile(t, filepath.Join(h.plugins, "hello.go"), reconcilerPluginSource)
|
||||
writeReconcilerFile(t, filepath.Join(h.secretsD, "hello.go"), reconcilerSecretSource)
|
||||
|
||||
if err := r.reconcile(t.Context()); err != nil {
|
||||
t.Fatalf("reconcile: %v", err)
|
||||
}
|
||||
if !h.root.Has("hello") {
|
||||
t.Error("dropped plugin was not loaded in place")
|
||||
}
|
||||
engine, ok := h.secrets.Get("hello")
|
||||
if !ok {
|
||||
t.Fatal("dropped secret engine was not loaded in place")
|
||||
}
|
||||
value, err := engine.Resolve("k")
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
if value != "one:k" {
|
||||
t.Errorf("Resolve() = %q, want one:k", value)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPluginReconcilerReplacesAnEditedSecretEngine(t *testing.T) {
|
||||
h := newReconcilerHarness(t)
|
||||
r := h.reconciler()
|
||||
r.seed()
|
||||
|
||||
path := filepath.Join(h.secretsD, "hello.go")
|
||||
writeReconcilerFile(t, path, reconcilerSecretSource)
|
||||
if err := r.reconcile(t.Context()); err != nil {
|
||||
t.Fatalf("first reconcile: %v", err)
|
||||
}
|
||||
|
||||
writeReconcilerFile(t, path, reconcilerEditedSecretSource)
|
||||
if err := r.reconcile(t.Context()); err != nil {
|
||||
t.Fatalf("second reconcile: %v", err)
|
||||
}
|
||||
engine, ok := h.secrets.Get("hello")
|
||||
if !ok {
|
||||
t.Fatal("edited secret engine disappeared")
|
||||
}
|
||||
value, err := engine.Resolve("k")
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
if value != "two:k" {
|
||||
t.Errorf("Resolve() after edit = %q, want the replaced two:k", value)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPluginReconcilerReportsARemovedFileThatKeepsRunning(t *testing.T) {
|
||||
h := newReconcilerHarness(t)
|
||||
r := h.reconciler()
|
||||
r.seed()
|
||||
|
||||
pluginPath := filepath.Join(h.plugins, "hello.go")
|
||||
secretPath := filepath.Join(h.secretsD, "hello.go")
|
||||
writeReconcilerFile(t, pluginPath, reconcilerPluginSource)
|
||||
writeReconcilerFile(t, secretPath, reconcilerSecretSource)
|
||||
if err := r.reconcile(t.Context()); err != nil {
|
||||
t.Fatalf("first reconcile: %v", err)
|
||||
}
|
||||
|
||||
if err := os.Remove(pluginPath); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Remove(secretPath); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err := r.reconcile(t.Context())
|
||||
if err == nil {
|
||||
t.Fatal("a reconcile after two removals reported no problem")
|
||||
}
|
||||
for _, want := range []string{"hello.go", "removed", "restart"} {
|
||||
if !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("removal report %q does not mention %q", err, want)
|
||||
}
|
||||
}
|
||||
// The running code is not unloaded: Yaegi has no unload path, so both the
|
||||
// module and the engine keep serving until the process restarts.
|
||||
if !h.root.Has("hello") {
|
||||
t.Error("a removed plugin stopped running")
|
||||
}
|
||||
if _, ok := h.secrets.Get("hello"); !ok {
|
||||
t.Error("a removed secret engine was unregistered")
|
||||
}
|
||||
|
||||
// Re-adding the file clears the removal: the replacement takes over and no
|
||||
// old interpreter is left serving the path.
|
||||
writeReconcilerFile(t, pluginPath, reconcilerPluginSource)
|
||||
writeReconcilerFile(t, secretPath, reconcilerSecretSource)
|
||||
if err := r.reconcile(t.Context()); err != nil {
|
||||
t.Fatalf("reconcile after re-adding the files: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPluginSettingsLiveUpdateLoadsTheNewDirectory(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeReconcilerFile(t, filepath.Join(dir, "hello.go"), reconcilerPluginSource)
|
||||
|
||||
running := fileConfig()
|
||||
b, status := newLiveApplyBoot(t, running)
|
||||
resources := databaseOwnedResources()
|
||||
resources[controlplane.PluginSettingsKind] = map[string]any{
|
||||
"plugin_dir": dir, "module_dir": "/db/modules", "secret_engine_dir": "/db/secrets", "skills_dir": "",
|
||||
}
|
||||
b.controlPlane = controlplane.NewRPCClient(&controlPlaneStub{values: resources})
|
||||
b.secrets = secret.NewRegistry()
|
||||
host := plugin.NewHost()
|
||||
if err := host.Start(t.Context()); err != nil {
|
||||
t.Fatalf("start host: %v", err)
|
||||
}
|
||||
b.pluginReconciler = newPluginReconciler(b.log, pluginReconcileTargets{
|
||||
host: host,
|
||||
secrets: b.secrets,
|
||||
modules: module.New(),
|
||||
dirs: func() config.Config { return b.cfgHolder.Get() },
|
||||
})
|
||||
b.pluginReconciler.seed()
|
||||
|
||||
b.applyRuntimeResourceUpdate(t.Context(), controlplane.PluginSettingsKind, controlplane.AppliedResource{Version: 2})
|
||||
|
||||
if got := b.cfgHolder.Get().PluginDir; got != dir {
|
||||
t.Fatalf("running plugin dir = %q, want the stored %q", got, dir)
|
||||
}
|
||||
if !host.Has("hello") {
|
||||
t.Fatal("a stored plugin_dir change did not load its plugin without a restart")
|
||||
}
|
||||
last, ok := status.last(controlplane.PluginSettingsKind)
|
||||
if !ok {
|
||||
t.Fatal("the live plugin-settings update reported no apply status")
|
||||
}
|
||||
if last.Error != "" {
|
||||
t.Errorf("apply status error = %q, want none for a live directory load", last.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPluginSettingsSkillsDirChangeIsRefusedOnTheLivePath(t *testing.T) {
|
||||
running := fileConfig()
|
||||
b, status := newLiveApplyBoot(t, running)
|
||||
// The stored document's skills_dir (/db/skills) differs from the running
|
||||
// empty value, and skills_dir has no live consumer.
|
||||
b.controlPlane = controlplane.NewRPCClient(&controlPlaneStub{values: databaseOwnedResources()})
|
||||
|
||||
b.applyRuntimeResourceUpdate(t.Context(), controlplane.PluginSettingsKind, controlplane.AppliedResource{Version: 2})
|
||||
|
||||
if got := b.cfgHolder.Get().PluginDir; got != fileConfig().PluginDir {
|
||||
t.Errorf("a refused plugin-settings document published plugin_dir %q, want the file's %q", got, fileConfig().PluginDir)
|
||||
}
|
||||
last, ok := status.last(controlplane.PluginSettingsKind)
|
||||
if !ok {
|
||||
t.Fatal("the refused plugin-settings update reported no apply status")
|
||||
}
|
||||
if !strings.Contains(last.Error, "skills_dir") {
|
||||
t.Errorf("apply status error = %q, want it to name skills_dir", last.Error)
|
||||
}
|
||||
if last.AppliedVersion != 2 {
|
||||
t.Errorf("apply status version = %d, want the refused version 2", last.AppliedVersion)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPluginReconcilerReportsTheApplyStatusTruth(t *testing.T) {
|
||||
h := newReconcilerHarness(t)
|
||||
var reported []error
|
||||
reported = nil
|
||||
r := newPluginReconciler(slog.New(slog.DiscardHandler), pluginReconcileTargets{
|
||||
host: h.root,
|
||||
secrets: h.secrets,
|
||||
modules: h.mods,
|
||||
dirs: func() config.Config { return h.cfg },
|
||||
report: func(_ context.Context, err error) { reported = append(reported, err) },
|
||||
})
|
||||
r.seed()
|
||||
|
||||
writeReconcilerFile(t, filepath.Join(h.secretsD, "hello.go"), reconcilerSecretSource)
|
||||
if err := r.reconcile(t.Context()); err != nil {
|
||||
t.Fatalf("clean reconcile: %v", err)
|
||||
}
|
||||
if len(reported) != 1 || reported[0] != nil {
|
||||
t.Fatalf("clean reconcile reported %v, want one nil (a live add is applied)", reported)
|
||||
}
|
||||
|
||||
if err := os.Remove(filepath.Join(h.secretsD, "hello.go")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.reconcile(t.Context()); err == nil {
|
||||
t.Fatal("removal reconcile reported no error")
|
||||
}
|
||||
if len(reported) != 2 || reported[1] == nil {
|
||||
t.Fatalf("removal reconcile reported %v, want the removal as the second record", reported)
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
// The State Store seeds provider-settings from the config it booted with, so
|
||||
// building its secret registry must leave every provider's source reference
|
||||
// in place rather than rewriting it to a process-local env name.
|
||||
func TestConfiguredSecretRegistryKeepsProviderReferences(t *testing.T) {
|
||||
ref := secret.SecretRef{Engine: "env", Key: "OPENAI_KEY"}
|
||||
t.Setenv("OPENAI_KEY", "sk-test")
|
||||
cfg := config.Config{Providers: map[string]config.Provider{"openai": {Class: "openai", APIKey: ref}}}
|
||||
|
||||
if _, err := configuredSecretRegistry(&cfg, slog.New(slog.DiscardHandler)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := cfg.Providers["openai"]
|
||||
if got.APIKey != ref || got.APIKeyEnv != "" {
|
||||
t.Fatalf("provider rewritten: api_key=%+v api_key_env=%q", got.APIKey, got.APIKeyEnv)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStateStoreBootSeedsProviderSourceReference(t *testing.T) {
|
||||
url := pgtest.URL(t)
|
||||
store := pgstore.On(pgstore.PoolAt(t, url))
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
ref := secret.SecretRef{Engine: "env", Key: "ARCHIE_TEST_PROVIDER_SOURCE"}
|
||||
t.Setenv(ref.Key, "provider-secret")
|
||||
body := fmt.Sprintf("bot_user = 'archie'\ndatabase_url = %q\n[providers.openai]\nclass = 'openai'\napi_key = {engine = 'env', key = %q}\n", url, ref.Key)
|
||||
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
errCh := make(chan error, 1)
|
||||
go func() { errCh <- RunStateStore(ctx, StateStoreOptions{Config: path, Listen: "127.0.0.1:0"}) }()
|
||||
deadline := time.After(10 * time.Second)
|
||||
for {
|
||||
resource, err := store.Resource(t.Context(), storecontract.DefaultOrgID, controlplane.ProviderSettingsKind)
|
||||
if err == nil {
|
||||
if strings.Contains(string(resource.Value), "ARCHIE_PROVIDER_") || !strings.Contains(string(resource.Value), ref.Key) {
|
||||
t.Fatalf("stored provider settings = %s, want source reference and no derived env name", resource.Value)
|
||||
}
|
||||
break
|
||||
}
|
||||
select {
|
||||
case bootErr := <-errCh:
|
||||
t.Fatalf("RunStateStore failed before provider import: %v", bootErr)
|
||||
case <-deadline:
|
||||
t.Fatalf("provider settings were not imported: %v", err)
|
||||
case <-time.After(25 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
if err := <-errCh; err != nil && !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("RunStateStore shutdown: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
// TestConnectNATSCreatesReactionStream pins the two JetStream streams the
|
||||
// daemon must provision alongside each other: ARCHIE_TASKS (work-queue task
|
||||
// distribution) and ARCHIE_REACTIONS (fan-out reaction delivery). Each case
|
||||
// asserts the ACTUAL stream configuration the embedded broker reports, not
|
||||
// just the Config struct that composed it.
|
||||
//
|
||||
// ARCHIE_REACTIONS must be a LimitsPolicy stream so two consumers on
|
||||
// overlapping filter subjects both receive a reaction (the trap documented in
|
||||
// CLAUDE.md), and it must carry a finite retention limit so acknowledged
|
||||
// reactions do not accumulate without bound. ARCHIE_TASKS must remain a
|
||||
// WorkQueuePolicy stream with no age/count/byte limit: acked messages are
|
||||
// discarded, so its only bound is outstanding work, and imposing a limit
|
||||
// could silently drop undelivered tasks.
|
||||
func TestConnectNATSCreatesReactionStream(t *testing.T) {
|
||||
b := &boot{
|
||||
cfg: config.Config{
|
||||
StateDir: t.TempDir(),
|
||||
NATS: config.NATSConfig{Mode: config.NATSModeEmbedded},
|
||||
},
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
}
|
||||
if err := b.connectNATS(t.Context()); err != nil {
|
||||
t.Fatalf("connectNATS = %v", err)
|
||||
}
|
||||
t.Cleanup(b.cleanup)
|
||||
|
||||
conn, err := natsio.Connect(b.natsURL, natsio.Token(b.natsToken))
|
||||
if err != nil {
|
||||
t.Fatalf("raw nats connect = %v", err)
|
||||
}
|
||||
t.Cleanup(conn.Close)
|
||||
|
||||
js, err := jetstream.New(conn)
|
||||
if err != nil {
|
||||
t.Fatalf("jetstream.New = %v", err)
|
||||
}
|
||||
|
||||
streamCases := []struct {
|
||||
name string
|
||||
stream string
|
||||
retention jetstream.RetentionPolicy
|
||||
subjects []string
|
||||
wantMaxAge time.Duration
|
||||
}{
|
||||
{
|
||||
name: "reactions fan-out with finite retention",
|
||||
stream: "ARCHIE_REACTIONS",
|
||||
retention: jetstream.LimitsPolicy,
|
||||
subjects: []string{"archie.reaction.>"},
|
||||
wantMaxAge: reactionStreamMaxAge,
|
||||
},
|
||||
{
|
||||
name: "tasks work-queue unchanged and unbounded",
|
||||
stream: "ARCHIE_TASKS",
|
||||
retention: jetstream.WorkQueuePolicy,
|
||||
subjects: []string{"archie.task.>"},
|
||||
// wantMaxAge zero asserts ARCHIE_TASKS stays unbounded by age.
|
||||
},
|
||||
}
|
||||
for _, tc := range streamCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
stream, err := js.Stream(t.Context(), tc.stream)
|
||||
if err != nil {
|
||||
t.Fatalf("js.Stream(%s) = %v", tc.stream, err)
|
||||
}
|
||||
info, err := stream.Info(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("stream.Info(%s) = %v", tc.stream, err)
|
||||
}
|
||||
if info.Config.Retention != tc.retention {
|
||||
t.Fatalf("%s retention = %v, want %v", tc.stream, info.Config.Retention, tc.retention)
|
||||
}
|
||||
for _, subject := range tc.subjects {
|
||||
if !slices.Contains(info.Config.Subjects, subject) {
|
||||
t.Errorf("%s subjects = %v, want to contain %s", tc.stream, info.Config.Subjects, subject)
|
||||
}
|
||||
}
|
||||
if info.Config.MaxAge != tc.wantMaxAge {
|
||||
t.Fatalf("%s MaxAge = %v, want %v", tc.stream, info.Config.MaxAge, tc.wantMaxAge)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Fan-out proof: two consumers on the same overlapping filter subject
|
||||
// both receive the one published message. A work-queue stream would
|
||||
// deliver it to only one of them.
|
||||
reactionStream, err := js.Stream(t.Context(), "ARCHIE_REACTIONS")
|
||||
if err != nil {
|
||||
t.Fatalf("js.Stream(ARCHIE_REACTIONS) = %v", err)
|
||||
}
|
||||
if _, err := js.PublishMsg(t.Context(), &natsio.Msg{
|
||||
Subject: "archie.reaction.test",
|
||||
Data: []byte("x"),
|
||||
}); err != nil {
|
||||
t.Fatalf("publish to archie.reaction.* = %v, want it to land in ARCHIE_REACTIONS", err)
|
||||
}
|
||||
|
||||
got := make(chan string, 2)
|
||||
fetch := func() {
|
||||
consumer, err := reactionStream.CreateOrUpdateConsumer(t.Context(), jetstream.ConsumerConfig{
|
||||
FilterSubject: "archie.reaction.>",
|
||||
AckPolicy: jetstream.AckExplicitPolicy,
|
||||
})
|
||||
if err != nil {
|
||||
t.Errorf("create reaction consumer: %v", err)
|
||||
return
|
||||
}
|
||||
batch, err := consumer.Fetch(1, jetstream.FetchMaxWait(5*time.Second))
|
||||
if err != nil {
|
||||
t.Errorf("reaction consumer fetch: %v", err)
|
||||
return
|
||||
}
|
||||
for msg := range batch.Messages() {
|
||||
if msg == nil {
|
||||
continue
|
||||
}
|
||||
got <- string(msg.Data())
|
||||
_ = msg.Ack()
|
||||
}
|
||||
}
|
||||
go fetch()
|
||||
go fetch()
|
||||
|
||||
var received []string
|
||||
deadline := time.After(10 * time.Second)
|
||||
for len(received) < 2 {
|
||||
select {
|
||||
case data := <-got:
|
||||
received = append(received, data)
|
||||
case <-deadline:
|
||||
t.Fatalf("fan-out: received %v, want both consumers to receive x", received)
|
||||
}
|
||||
}
|
||||
for _, data := range received {
|
||||
if data != "x" {
|
||||
t.Errorf("reaction consumer received %q, want x", data)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
|
||||
func TestDiskProbePath_PrefersStateDir(t *testing.T) {
|
||||
cfg := config.Config{StateDir: "/var/lib/archie", WorkDir: "/srv/archie"}
|
||||
if got := diskProbePath(cfg); got != "/var/lib/archie" {
|
||||
t.Fatalf("diskProbePath = %q, want /var/lib/archie", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskProbePath_FallsBackToWorkDir(t *testing.T) {
|
||||
cfg := config.Config{WorkDir: "/srv/archie"}
|
||||
if got := diskProbePath(cfg); got != "/srv/archie" {
|
||||
t.Fatalf("diskProbePath = %q, want /srv/archie", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskProbePath_FallsBackToCwd(t *testing.T) {
|
||||
if got := diskProbePath(config.Config{}); got != "." {
|
||||
t.Fatalf("diskProbePath = %q, want .", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPingChat_ReportsUnwiredChat pins that a daemon with no Gateway contract
|
||||
// degrades its gateway probe rather than passing it: chat is served entirely
|
||||
// by the Gateway now, so an unwired contract means no chat at all.
|
||||
func TestPingChat_ReportsUnwiredChat(t *testing.T) {
|
||||
if err := pingChat(context.Background(), nil); err == nil {
|
||||
t.Fatal("pingChat(nil chat) = nil, want an error")
|
||||
}
|
||||
if err := pingChat(context.Background(), &webui.ChatService{}); err == nil {
|
||||
t.Fatal("pingChat(unwired contract) = nil, want an error")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetupReadinessProbes_WiresEverySubsystem proves the composition root
|
||||
// registers all five readiness probes and that the registry surfaces them in
|
||||
// the detailed report. It does not assert their status -- real state depends
|
||||
// on the store, config, disk, model and gateway in the running daemon -- only
|
||||
// that every subsystem the epic names is actually wired.
|
||||
func TestSetupReadinessProbes_WiresEverySubsystem(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
cfg := config.Config{
|
||||
BotUser: "archie-bot",
|
||||
PollInterval: config.Duration(60_000_000_000), // 60s, satisfies validate
|
||||
Dispatch: config.Dispatch{Trigger: "assignee"},
|
||||
Forge: config.Forge{Type: "none"},
|
||||
Containers: config.ContainerConfig{
|
||||
Image: "ghcr.io/samcharles93/archie-agent:latest",
|
||||
},
|
||||
Providers: map[string]config.Provider{
|
||||
"openai": {Class: "openai"},
|
||||
},
|
||||
}
|
||||
|
||||
b := &boot{
|
||||
st: st,
|
||||
cfgHolder: config.NewHolder(cfg),
|
||||
chat: &webui.ChatService{
|
||||
Contract: &gateway.LocalChatAdapter{
|
||||
Router: &gateway.Router{},
|
||||
Sessions: gateway.NewSessionStoreMemory(),
|
||||
Models: newChatModelManager(map[string]string{"chat": "openai/gpt-4o"}, nil),
|
||||
},
|
||||
},
|
||||
chatModels: newChatModelManager(map[string]string{"chat": "openai/gpt-4o"}, nil),
|
||||
cfg: cfg,
|
||||
}
|
||||
|
||||
b.setupReadinessProbes()
|
||||
if b.healthRegistry == nil {
|
||||
t.Fatal("b.healthRegistry is nil after setupReadinessProbes")
|
||||
}
|
||||
|
||||
report := b.healthRegistry.Run(context.Background())
|
||||
got := map[string]int{}
|
||||
for _, c := range report.Components {
|
||||
got[c.Name]++
|
||||
}
|
||||
for _, name := range []string{"state_db", "config", "disk", "model", "gateway"} {
|
||||
if got[name] != 1 {
|
||||
t.Errorf("component %q registered %d times, want 1: %+v", name, got[name], report.Components)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,276 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
)
|
||||
|
||||
// writeConfig writes a TOML config file. The minimal shape (bot_user +
|
||||
// one repo) is the same fixture loader_test.go uses to satisfy
|
||||
// validation.
|
||||
func writeConfig(t *testing.T, path, body string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func minimalConfigTOML(botUser string) string {
|
||||
return "bot_user = \"" + botUser + "\"\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
}
|
||||
|
||||
// invalidConfigTOML carries a value the bootstrap document still owns, so
|
||||
// resolving it fails. The settings the control plane owns are no longer judged
|
||||
// at load, so using one of those here would silently turn these tests into a
|
||||
// false pass.
|
||||
func invalidConfigTOML() string {
|
||||
return "bot_user = \"widget\"\n[memory]\nengine = \"not-a-real-engine\"\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
}
|
||||
|
||||
func TestReloadAppliesAndPublishes(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.toml")
|
||||
writeConfig(t, path, minimalConfigTOML("first"))
|
||||
|
||||
loader := configuration.New(slog.New(slog.DiscardHandler))
|
||||
var published config.Config
|
||||
controller := newReloadController(loader, path, "", func(_ context.Context, doc *configuration.Document) error {
|
||||
published = doc.Config
|
||||
return nil
|
||||
})
|
||||
|
||||
if err := controller.Reload(t.Context()); err != nil {
|
||||
t.Fatalf("first reload: %v", err)
|
||||
}
|
||||
if published.BotUser != "first" {
|
||||
t.Fatalf("published BotUser = %q, want first", published.BotUser)
|
||||
}
|
||||
|
||||
writeConfig(t, path, minimalConfigTOML("second"))
|
||||
if err := controller.Reload(t.Context()); err != nil {
|
||||
t.Fatalf("second reload: %v", err)
|
||||
}
|
||||
if published.BotUser != "second" {
|
||||
t.Fatalf("published BotUser = %q, want second", published.BotUser)
|
||||
}
|
||||
if st := controller.Status(); st.LastReloadAt == "" || st.LastError != "" {
|
||||
t.Fatalf("Status after success = %+v, want LastReloadAt set and no error", st)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReloadValidationFailureDoesNotApply pins the safety property of
|
||||
// the whole reload feature: a reload that fails validation must not
|
||||
// publish. If apply were called on the error path, a bad file would
|
||||
// half-apply or corrupt the running config.
|
||||
func TestReloadValidationFailureDoesNotApply(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.toml")
|
||||
writeConfig(t, path, minimalConfigTOML("widget"))
|
||||
|
||||
loader := configuration.New(slog.New(slog.DiscardHandler))
|
||||
applied := 0
|
||||
controller := newReloadController(loader, path, "", func(context.Context, *configuration.Document) error { applied++; return nil })
|
||||
|
||||
if err := controller.Reload(t.Context()); err != nil {
|
||||
t.Fatalf("first reload: %v", err)
|
||||
}
|
||||
if applied != 1 {
|
||||
t.Fatalf("apply called %d times after successful reload, want 1", applied)
|
||||
}
|
||||
|
||||
writeConfig(t, path, invalidConfigTOML())
|
||||
err := controller.Reload(t.Context())
|
||||
if err == nil {
|
||||
t.Fatal("reload with invalid config: expected an error")
|
||||
}
|
||||
if applied != 1 {
|
||||
t.Fatalf("apply called %d times after failed reload, want still 1", applied)
|
||||
}
|
||||
if st := controller.Status(); st.LastError == "" || st.LastErrorAt == "" {
|
||||
t.Fatalf("Status after failed reload = %+v, want LastError and LastErrorAt set", st)
|
||||
}
|
||||
|
||||
// A subsequent valid reload clears the error.
|
||||
writeConfig(t, path, minimalConfigTOML("widget"))
|
||||
if err := controller.Reload(t.Context()); err != nil {
|
||||
t.Fatalf("recovery reload: %v", err)
|
||||
}
|
||||
if st := controller.Status(); st.LastError != "" || st.LastReloadAt == "" {
|
||||
t.Fatalf("Status after recovery = %+v, want no error and a reload time", st)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReloadApplyFailureIsRecorded pins the other half of the safety
|
||||
// property: a file that loads cleanly can still fail to apply, because the
|
||||
// database layer reloadConfig re-applies comes from the control plane. That
|
||||
// failure must be recorded and returned, not reported as a successful
|
||||
// reload.
|
||||
func TestReloadApplyFailureIsRecorded(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.toml")
|
||||
writeConfig(t, path, minimalConfigTOML("widget"))
|
||||
|
||||
loader := configuration.New(slog.New(slog.DiscardHandler))
|
||||
controller := newReloadController(loader, path, "", func(context.Context, *configuration.Document) error {
|
||||
return errors.New("runtime settings unavailable")
|
||||
})
|
||||
|
||||
if err := controller.Reload(t.Context()); err == nil {
|
||||
t.Fatal("reload with a failing apply: expected an error")
|
||||
}
|
||||
st := controller.Status()
|
||||
if st.LastError == "" || st.LastErrorAt == "" {
|
||||
t.Fatalf("Status after a failed apply = %+v, want LastError and LastErrorAt set", st)
|
||||
}
|
||||
if st.LastReloadAt != "" {
|
||||
t.Fatalf("Status after a failed apply recorded a reload time: %+v", st)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReloadLoopAppliesOnSignalAndStopsOnCancel(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.toml")
|
||||
writeConfig(t, path, minimalConfigTOML("widget"))
|
||||
|
||||
loader := configuration.New(slog.New(slog.DiscardHandler))
|
||||
applied := make(chan struct{}, 1)
|
||||
controller := newReloadController(loader, path, "", func(context.Context, *configuration.Document) error {
|
||||
applied <- struct{}{}
|
||||
return nil
|
||||
})
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
ch := make(chan os.Signal, 1)
|
||||
var wg sync.WaitGroup
|
||||
wg.Go(func() {
|
||||
reloadLoop(ctx, ch, controller, slog.New(slog.DiscardHandler))
|
||||
})
|
||||
|
||||
ch <- syscall.SIGHUP
|
||||
select {
|
||||
case <-applied:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("reload not applied after signal")
|
||||
}
|
||||
|
||||
cancel()
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestChangedNonReloadableFields(t *testing.T) {
|
||||
base := config.Config{
|
||||
BotUser: "a",
|
||||
MaxRetries: 3,
|
||||
PollInterval: config.Duration(30 * time.Second),
|
||||
Repos: []config.Repo{{Owner: "x", Name: "y"}},
|
||||
}
|
||||
|
||||
// Unchanged -> empty.
|
||||
if got := changedNonReloadableFields(base, base); len(got) != 0 {
|
||||
t.Fatalf("unchanged: got %v, want []", got)
|
||||
}
|
||||
|
||||
// Reloadable-only changes -> empty.
|
||||
reloadableOnly := base
|
||||
reloadableOnly.PollInterval = config.Duration(60 * time.Second)
|
||||
reloadableOnly.Repos = []config.Repo{{Owner: "x", Name: "z"}}
|
||||
reloadableOnly.Budgets = config.Budgets{MaxSteps: 99}
|
||||
reloadableOnly.Dispatch = config.Dispatch{Trigger: "label"}
|
||||
reloadableOnly.DiffCapLines = new(1234)
|
||||
reloadableOnly.Models = map[string]string{"builder": "provider/model"}
|
||||
reloadableOnly.Notify = config.Notify{Webhook: "https://notify.example/hook"}
|
||||
reloadableOnly.Label = "archie"
|
||||
reloadableOnly.BotUser = "new-bot"
|
||||
reloadableOnly.Forge = config.Forge{Host: "https://new-forge.example"}
|
||||
reloadableOnly.MaxRetries = 5
|
||||
if got := changedNonReloadableFields(base, reloadableOnly); len(got) != 0 {
|
||||
t.Fatalf("reloadable-only: got %v, want []", got)
|
||||
}
|
||||
|
||||
// Containers sub-field granularity: the fields the pool re-reads per
|
||||
// acquire, and the concurrency cap the dispatcher resizes on, are
|
||||
// reloadable; RegistryAuth stays frozen in the startup-built pool.
|
||||
c1 := base
|
||||
c1.Containers = config.ContainerConfig{Image: "img1", MaxConcurrency: 2, VolumeTTL: config.Duration(24 * time.Hour)}
|
||||
c2 := c1
|
||||
c2.Containers.Image = "img2"
|
||||
if got := changedNonReloadableFields(c1, c2); len(got) != 0 {
|
||||
t.Fatalf("Image change: got %v, want [] (the pool reads it per acquire)", got)
|
||||
}
|
||||
c3 := c1
|
||||
c3.Containers.MaxConcurrency = 4
|
||||
if got := changedNonReloadableFields(c1, c3); len(got) != 0 {
|
||||
t.Fatalf("MaxConcurrency change: got %v, want [] (the pool reads it and the dispatcher resizes)", got)
|
||||
}
|
||||
c4 := c1
|
||||
c4.Containers.VolumeTTL = config.Duration(48 * time.Hour)
|
||||
if got := changedNonReloadableFields(c1, c4); len(got) != 0 {
|
||||
t.Fatalf("VolumeTTL change: got %v, want []", got)
|
||||
}
|
||||
c5 := c1
|
||||
c5.Containers.RegistryAuth = config.SecretRef{Engine: "env", Key: "REGISTRY_AUTH"}
|
||||
if got := changedNonReloadableFields(c1, c5); len(got) != 1 || got[0] != "Containers.RegistryAuth" {
|
||||
t.Fatalf("RegistryAuth change: got %v, want [Containers.RegistryAuth] (the pool resolves it at boot)", got)
|
||||
}
|
||||
|
||||
// NATS is not reloadable: a URL change warns (the daemon's client is
|
||||
// startup-built; containers get the frozen ConnectedNATS).
|
||||
natsChanged := base
|
||||
natsChanged.NATS = config.NATSConfig{URL: "nats://new:4222"}
|
||||
if got := changedNonReloadableFields(base, natsChanged); len(got) != 1 || got[0] != "NATS" {
|
||||
t.Fatalf("NATS change: got %v, want [NATS]", got)
|
||||
}
|
||||
|
||||
// Forge.Host is reloadable but Forge.Type is not: only the host is
|
||||
// carried into TaskContext by ForTask.
|
||||
forgeTypeChanged := base
|
||||
forgeTypeChanged.Forge = config.Forge{Type: "gitea"}
|
||||
if got := changedNonReloadableFields(base, forgeTypeChanged); len(got) != 1 || got[0] != "Forge.Type" {
|
||||
t.Fatalf("Forge.Type change: got %v, want [Forge.Type]", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReloadableFieldsCoverForTaskSnapshot pins the allowlist against
|
||||
// the per-dispatch snapshot: every field ForTask carries into a
|
||||
// TaskContext is re-read at dispatch, so a reload applies to new tasks.
|
||||
// If a field is added to ForTask later, this test fails until the
|
||||
// allowlist is updated -- a hand-maintained list that mirrors ForTask
|
||||
// otherwise drifts silently into a wrong 'requires a restart' warning.
|
||||
func TestReloadableFieldsCoverForTaskSnapshot(t *testing.T) {
|
||||
tt := reflect.TypeFor[config.TaskConfig]()
|
||||
for field := range tt.Fields() {
|
||||
name := field.Name
|
||||
if name == "Forge" {
|
||||
// TaskConfig.Forge is TaskForge{Host}; it maps to the
|
||||
// Config.Forge.Host sub-field allowlist entry.
|
||||
if !reloadableSubFields["Forge"]["Host"] {
|
||||
t.Errorf("ForTask field Forge (Host) is not allowlisted as reloadable")
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !reloadableFields[name] {
|
||||
t.Errorf("ForTask field %s is not allowlisted as reloadable", name)
|
||||
}
|
||||
}
|
||||
// Label is not carried by ForTask; BotUser now is, but it is also read
|
||||
// on the poll path independently of the task snapshot. Pin both by hand
|
||||
// so a refactor that moves either read site -- including one that drops
|
||||
// BotUser from ForTask again -- does not silently drop the allowlist
|
||||
// entry the poll path still depends on.
|
||||
for _, name := range []string{"Label", "BotUser"} {
|
||||
if !reloadableFields[name] {
|
||||
t.Errorf("poll-path field %s is not allowlisted as reloadable", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// TestBuildDaemonCarriesWorkflowRoutingBindings pins the composition hop in the
|
||||
// cross-process routing fix: the resolved bindings loaded by loadWorkflowRouting
|
||||
// must survive buildDaemon onto the daemon that puts them into taskrun.Request.
|
||||
//
|
||||
// Without this, a nil here reverts the entire fix while every other test stays
|
||||
// green: the daemon test sets d.KindWorkflows itself, and the worker test drives
|
||||
// routeTask directly, so neither observes how the daemon obtained them. That is
|
||||
// the "tested in isolation, never verified wired" shape this repo has been bitten
|
||||
// by before.
|
||||
func TestBuildDaemonCarriesWorkflowRoutingBindings(t *testing.T) {
|
||||
storeA := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = storeA.Close() })
|
||||
storeB := openSecondStore(t)
|
||||
|
||||
b := &boot{
|
||||
cfg: config.Config{},
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
st: storeA,
|
||||
stateStore: storeB,
|
||||
kindWorkflows: workflow.KindWorkflows{workintake.KindBug: "custom-bug"},
|
||||
labelWorkflows: workflow.LabelWorkflows{"security": "security-review"},
|
||||
}
|
||||
b.buildDaemon()
|
||||
|
||||
if got := b.d.KindWorkflows[workintake.KindBug]; got != "custom-bug" {
|
||||
t.Fatalf("Daemon.KindWorkflows[bug] = %q, want %q; buildDaemon dropped the kind routing bindings, so the worker would route with built-in defaults", got, "custom-bug")
|
||||
}
|
||||
if got := b.d.LabelWorkflows["security"]; got != "security-review" {
|
||||
t.Fatalf("Daemon.LabelWorkflows[security] = %q, want %q; buildDaemon dropped the label routing bindings", got, "security-review")
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
)
|
||||
|
||||
// fakeTaskCreator records CreateTask calls so a test can assert the
|
||||
// scheduling engine's workflow runner reaches a real gateway.TaskCreator
|
||||
// rather than a no-op.
|
||||
type fakeTaskCreator struct {
|
||||
calls []gateway.SpawnRequest
|
||||
}
|
||||
|
||||
func (f *fakeTaskCreator) CreateTask(_ context.Context, req gateway.SpawnRequest) (int64, error) {
|
||||
f.calls = append(f.calls, req)
|
||||
return int64(len(f.calls)), nil
|
||||
}
|
||||
|
||||
func newTestBoot(t *testing.T, tasks gateway.TaskCreator) *boot {
|
||||
t.Helper()
|
||||
bus := events.NewBus()
|
||||
t.Cleanup(bus.Close)
|
||||
return &boot{
|
||||
log: slog.New(slog.NewTextHandler(os.Stderr, nil)),
|
||||
bus: bus,
|
||||
doc: &configuration.Document{},
|
||||
cfg: config.Config{},
|
||||
chatTasks: tasks,
|
||||
defaultChatIdentity: "primary",
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetupSchedulingConstructsEngine is the red case for app-archied-2 /
|
||||
// scheduling-1 / config-2: schedulingConfig translated a valid
|
||||
// [scheduling] input but nothing at boot ever constructed the ticker
|
||||
// engine, so the whole scheduling/cron family was reachable from no
|
||||
// binary. setupScheduling is the composition site; this asserts it
|
||||
// actually produces a running-capable engine wired to a real
|
||||
// gateway.TaskCreator, not just a translated config struct.
|
||||
func TestSetupSchedulingConstructsEngine(t *testing.T) {
|
||||
creator := &fakeTaskCreator{}
|
||||
b := newTestBoot(t, creator)
|
||||
|
||||
if err := b.setupScheduling(); err != nil {
|
||||
t.Fatalf("setupScheduling() error = %v", err)
|
||||
}
|
||||
if b.schedulingEngine == nil {
|
||||
t.Fatal("setupScheduling() left b.schedulingEngine nil; the ticker engine was never constructed")
|
||||
}
|
||||
if len(b.cleanups) == 0 {
|
||||
t.Fatal("setupScheduling() registered no cleanup; engine/store would leak at shutdown")
|
||||
}
|
||||
|
||||
if err := b.schedulingEngine.Start(t.Context()); err != nil {
|
||||
t.Fatalf("schedulingEngine.Start() error = %v", err)
|
||||
}
|
||||
b.cleanup()
|
||||
}
|
||||
|
||||
// TestSetupSchedulingWorkflowRunnerReachesTaskCreator proves the "workflow"
|
||||
// kind runner registered on the router is backed by the real
|
||||
// gateway.TaskCreator this composition root already has, not a stub.
|
||||
func TestSetupSchedulingWorkflowRunnerReachesTaskCreator(t *testing.T) {
|
||||
creator := &fakeTaskCreator{}
|
||||
b := newTestBoot(t, creator)
|
||||
|
||||
if err := b.setupScheduling(); err != nil {
|
||||
t.Fatalf("setupScheduling() error = %v", err)
|
||||
}
|
||||
t.Cleanup(b.cleanup)
|
||||
|
||||
submitter := spawnTaskSubmitter{creator: b.chatTasks, identity: b.defaultChatIdentity}
|
||||
if err := submitter.Submit(context.Background(), "job-1", "title", "body"); err != nil {
|
||||
t.Fatalf("Submit() error = %v", err)
|
||||
}
|
||||
if len(creator.calls) != 1 {
|
||||
t.Fatalf("CreateTask called %d times, want 1", len(creator.calls))
|
||||
}
|
||||
if got := creator.calls[0]; got.Title != "title" || got.Body != "body" || got.Identity != "primary" {
|
||||
t.Errorf("CreateTask request = %+v, want Title=title Body=body Identity=primary", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetupSchedulingWithoutTaskCreatorLeavesEngineNil documents the one
|
||||
// deliberate degrade: no chat task creator configured means no runner can
|
||||
// honestly back the "workflow" kind, so the engine is left unstarted rather
|
||||
// than built with no reachable job kind.
|
||||
func TestSetupSchedulingWithoutTaskCreatorLeavesEngineNil(t *testing.T) {
|
||||
b := newTestBoot(t, nil)
|
||||
|
||||
if err := b.setupScheduling(); err != nil {
|
||||
t.Fatalf("setupScheduling() error = %v", err)
|
||||
}
|
||||
if b.schedulingEngine != nil {
|
||||
t.Fatal("setupScheduling() built an engine with no chat task creator configured")
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
)
|
||||
|
||||
func TestSchedulingConfigTranslatesExternalInput(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input configuration.SchedulingInput
|
||||
wantInterval time.Duration
|
||||
wantMaxParallel int
|
||||
wantJobTimeout time.Duration
|
||||
}{
|
||||
{
|
||||
name: "defaults",
|
||||
wantInterval: time.Minute,
|
||||
wantMaxParallel: 4,
|
||||
wantJobTimeout: time.Hour,
|
||||
},
|
||||
{
|
||||
name: "configured",
|
||||
input: configuration.SchedulingInput{
|
||||
Interval: configuration.Duration(30 * time.Second),
|
||||
MaxParallel: 2,
|
||||
JobTimeout: configuration.Duration(5 * time.Minute),
|
||||
},
|
||||
wantInterval: 30 * time.Second,
|
||||
wantMaxParallel: 2,
|
||||
wantJobTimeout: 5 * time.Minute,
|
||||
},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, err := schedulingConfig(tc.input, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Interval != tc.wantInterval || got.MaxParallel != tc.wantMaxParallel || got.JobTimeout != tc.wantJobTimeout {
|
||||
t.Errorf("schedulingConfig() = %+v, want interval=%v max_parallel=%d job_timeout=%v",
|
||||
got, tc.wantInterval, tc.wantMaxParallel, tc.wantJobTimeout)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchedulingConfigRejectsInvalidInput(t *testing.T) {
|
||||
tests := []configuration.SchedulingInput{
|
||||
{Interval: configuration.Duration(-time.Second)},
|
||||
{MaxParallel: -1},
|
||||
{JobTimeout: configuration.Duration(-time.Second)},
|
||||
{EventsSink: "kafka"},
|
||||
}
|
||||
for _, input := range tests {
|
||||
if _, err := schedulingConfig(input, nil); !errors.Is(err, configuration.ErrInvalidInput) {
|
||||
t.Errorf("schedulingConfig(%+v) error = %v, want ErrInvalidInput", input, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchedulingConfigSelectsEventSink(t *testing.T) {
|
||||
bus := events.NewBus()
|
||||
t.Cleanup(bus.Close)
|
||||
|
||||
for _, mode := range []string{"", configuration.EventsSinkNone} {
|
||||
cfg, err := schedulingConfig(configuration.SchedulingInput{EventsSink: mode}, bus)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Events != nil {
|
||||
t.Errorf("events_sink %q produced a sink", mode)
|
||||
}
|
||||
}
|
||||
cfg, err := schedulingConfig(configuration.SchedulingInput{EventsSink: configuration.EventsSinkBus}, bus)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Events == nil {
|
||||
t.Fatal("events_sink bus produced no sink")
|
||||
}
|
||||
}
|
||||
@@ -1,349 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/daemon"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
"github.com/samcharles93/archie-core/internal/sdnotify"
|
||||
)
|
||||
|
||||
// The protocol-level properties of the notify client -- the '@' address form,
|
||||
// the disabled and unusable socket contract, and the half-of-WatchdogSec
|
||||
// heartbeat -- are pinned in internal/sdnotify, where the client now lives.
|
||||
// These tests pin what is the daemon's: that its three serving entry points
|
||||
// announce, that the sampler samples daemon.LastPollAt, and that the whole
|
||||
// path stays silent and harmless without a NOTIFY_SOCKET.
|
||||
|
||||
// notifyRecorder captures every record at every level. The other recording
|
||||
// handler in this package keeps warnings only; these tests need "this path
|
||||
// logged nothing at all" as positive evidence that a disabled notifier stayed
|
||||
// silent, so the level has to be part of what is captured.
|
||||
type notifyRecorder struct {
|
||||
mu sync.Mutex
|
||||
records []slog.Record
|
||||
}
|
||||
|
||||
func (h *notifyRecorder) Enabled(context.Context, slog.Level) bool { return true }
|
||||
|
||||
func (h *notifyRecorder) Handle(_ context.Context, r slog.Record) error {
|
||||
// The Record is the caller's to reuse once Handle returns, so keep a copy.
|
||||
rec := r.Clone()
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.records = append(h.records, rec)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *notifyRecorder) WithAttrs([]slog.Attr) slog.Handler { return h }
|
||||
func (h *notifyRecorder) WithGroup(string) slog.Handler { return h }
|
||||
|
||||
func (h *notifyRecorder) all() []slog.Record {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
return append([]slog.Record(nil), h.records...)
|
||||
}
|
||||
|
||||
// at returns the captured records at one level.
|
||||
func (h *notifyRecorder) at(level slog.Level) []slog.Record {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
var out []slog.Record
|
||||
for _, r := range h.records {
|
||||
if r.Level == level {
|
||||
out = append(out, r)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// notifyListener is a stand-in for systemd's NOTIFY_SOCKET: a unixgram socket
|
||||
// that collects the state lines the daemon sends. It is bound to the real
|
||||
// NOTIFY_SOCKET for the duration of the test.
|
||||
type notifyListener struct {
|
||||
conn *net.UnixConn
|
||||
}
|
||||
|
||||
func newNotifyListener(t *testing.T) *notifyListener {
|
||||
t.Helper()
|
||||
// A unix socket path is capped near 108 bytes; the short file name keeps the
|
||||
// path inside t.TempDir() under that for any test name.
|
||||
return listenNotify(t, filepath.Join(t.TempDir(), "n.sock"))
|
||||
}
|
||||
|
||||
// listenNotify binds a notify socket at addr and points NOTIFY_SOCKET at it.
|
||||
func listenNotify(t *testing.T, addr string) *notifyListener {
|
||||
t.Helper()
|
||||
conn, err := net.ListenUnixgram("unixgram", &net.UnixAddr{Name: addr, Net: "unixgram"})
|
||||
if err != nil {
|
||||
t.Fatalf("listen for notify datagrams at %q: %v", addr, err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
t.Setenv(sdnotify.NotifySocketEnv, addr)
|
||||
return ¬ifyListener{conn: conn}
|
||||
}
|
||||
|
||||
// states drains every state line received within window.
|
||||
func (l *notifyListener) states(t *testing.T, window time.Duration) []string {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(window)
|
||||
var got []string
|
||||
buf := make([]byte, 1024)
|
||||
for {
|
||||
if err := l.conn.SetReadDeadline(deadline); err != nil {
|
||||
t.Fatalf("set notify read deadline: %v", err)
|
||||
}
|
||||
n, _, err := l.conn.ReadFromUnix(buf)
|
||||
if err != nil {
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) && netErr.Timeout() {
|
||||
return got
|
||||
}
|
||||
t.Fatalf("read notify datagram: %v", err)
|
||||
}
|
||||
got = append(got, string(buf[:n]))
|
||||
}
|
||||
}
|
||||
|
||||
// countState counts the datagrams carrying want among the received states.
|
||||
func countState(states []string, want string) int {
|
||||
n := 0
|
||||
for _, state := range states {
|
||||
if state == want {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// waitForState reads datagrams until one carries want or the window closes.
|
||||
// The states drain above collects a window's worth; a boot-path test waiting
|
||||
// for one state returns as soon as it arrives.
|
||||
func (l *notifyListener) waitForState(t *testing.T, window time.Duration, want string) bool {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(window)
|
||||
buf := make([]byte, 1024)
|
||||
for time.Now().Before(deadline) {
|
||||
if err := l.conn.SetReadDeadline(time.Now().Add(50 * time.Millisecond)); err != nil {
|
||||
t.Fatalf("set notify read deadline: %v", err)
|
||||
}
|
||||
n, _, err := l.conn.ReadFromUnix(buf)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if string(buf[:n]) == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// newNotifyTestBoot builds the composition the notify path reads: a boot whose
|
||||
// config holder supplies the run loop's poll cadence, and a real daemon whose
|
||||
// own poll loop stamps the progress marker the heartbeat sampler samples.
|
||||
func newNotifyTestBoot(t *testing.T, cadence time.Duration) (*boot, *daemon.Daemon) {
|
||||
t.Helper()
|
||||
cfg := config.Config{PollInterval: config.Duration(cadence)}
|
||||
holder := config.NewHolder(cfg)
|
||||
st := pgstore.Open(t)
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
d := &daemon.Daemon{Cfg: holder, Store: st, Log: log}
|
||||
return &boot{cfg: cfg, cfgHolder: holder, d: d, log: log}, d
|
||||
}
|
||||
|
||||
// pollPasses drives the daemon's poll passes the way Run does, one Cycle per
|
||||
// tick, while on is set. The progress marker is stamped by the daemon inside
|
||||
// Cycle, never by the test: what the sampler samples is the loop's own
|
||||
// evidence, not a value the test wrote.
|
||||
func pollPasses(ctx context.Context, d *daemon.Daemon, on *atomic.Bool, every time.Duration) {
|
||||
ticker := time.NewTicker(every)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if on.Load() {
|
||||
d.Cycle(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestNotifyReadyAndWatchdogHeartbeat is the run-loop path end to end: a real
|
||||
// NOTIFY_SOCKET, the daemon's own boot path announcing READY, and the run
|
||||
// loop's own progress marker producing WATCHDOG heartbeats.
|
||||
func TestNotifyReadyAndWatchdogHeartbeat(t *testing.T) {
|
||||
listener := newNotifyListener(t)
|
||||
t.Setenv(sdnotify.WatchdogUsecEnv, "20000") // 20ms watchdog: heartbeat every 10ms
|
||||
|
||||
b, d := newNotifyTestBoot(t, 50*time.Millisecond)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
|
||||
var polling atomic.Bool
|
||||
polling.Store(true)
|
||||
go pollPasses(ctx, d, &polling, 5*time.Millisecond)
|
||||
|
||||
b.announceReady()
|
||||
b.startWatchdog(ctx)
|
||||
|
||||
states := listener.states(t, 300*time.Millisecond)
|
||||
if !slices.Contains(states, sdnotify.ReadyState) {
|
||||
t.Errorf("states received = %v, want %q among them", states, sdnotify.ReadyState)
|
||||
}
|
||||
if countState(states, sdnotify.WatchdogState) == 0 {
|
||||
t.Errorf("states received = %v, want at least one %q among them", states, sdnotify.WatchdogState)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWatchdogWithholdsHeartbeatWhenRunLoopStalls is the semantic that makes
|
||||
// the heartbeat worth having: the beats stop once the loop stops making
|
||||
// progress, so a wedged event loop trips systemd's watchdog instead of being
|
||||
// kept alive by an independent ticker.
|
||||
func TestWatchdogWithholdsHeartbeatWhenRunLoopStalls(t *testing.T) {
|
||||
listener := newNotifyListener(t)
|
||||
t.Setenv(sdnotify.WatchdogUsecEnv, "20000") // 20ms watchdog: heartbeat every 10ms
|
||||
|
||||
const cadence = 50 * time.Millisecond
|
||||
b, d := newNotifyTestBoot(t, cadence)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
|
||||
var polling atomic.Bool
|
||||
polling.Store(true)
|
||||
go pollPasses(ctx, d, &polling, 5*time.Millisecond)
|
||||
|
||||
b.startWatchdog(ctx)
|
||||
if beats := countState(listener.states(t, 200*time.Millisecond), sdnotify.WatchdogState); beats == 0 {
|
||||
t.Fatal("no WATCHDOG=1 within 200ms while the run loop was polling")
|
||||
}
|
||||
|
||||
// From here the loop is inside a pass that never returns: nothing stamps
|
||||
// the progress marker again.
|
||||
polling.Store(false)
|
||||
|
||||
// Discard the beats the last stamp still licenses. The marker counts as
|
||||
// stale only once it is older than the loop's own cadence (50ms), and
|
||||
// samples are 10ms apart, so 150ms covers every remaining beat with margin.
|
||||
listener.states(t, 150*time.Millisecond)
|
||||
|
||||
if late := listener.states(t, 300*time.Millisecond); len(late) != 0 {
|
||||
t.Errorf("received %v after the run loop stalled, want no heartbeats", late)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNotifyUnsetIsNoOp pins the deployment contract: with no NOTIFY_SOCKET the
|
||||
// process behaves exactly as it did before sd_notify existed. Docker, a plain
|
||||
// terminal, and a systemd unit with no WatchdogSec all take this path, and none
|
||||
// of them may see a datagram, a warning, or a failed start.
|
||||
func TestNotifyUnsetIsNoOp(t *testing.T) {
|
||||
t.Setenv(sdnotify.WatchdogUsecEnv, "20000")
|
||||
// t.Setenv cannot unset a variable: register the restoration first, then
|
||||
// remove it for real so "unset" means unset.
|
||||
t.Setenv(sdnotify.NotifySocketEnv, "")
|
||||
if err := os.Unsetenv(sdnotify.NotifySocketEnv); err != nil {
|
||||
t.Fatalf("unset %s: %v", sdnotify.NotifySocketEnv, err)
|
||||
}
|
||||
|
||||
rec := ¬ifyRecorder{}
|
||||
b, _ := newNotifyTestBoot(t, 50*time.Millisecond)
|
||||
b.log = slog.New(rec)
|
||||
|
||||
b.announceReady()
|
||||
b.startWatchdog(t.Context())
|
||||
|
||||
if got := rec.all(); len(got) != 0 {
|
||||
t.Errorf("with NOTIFY_SOCKET unset the notify path logged %d records, want none: %v", len(got), got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNotifySocketFailureIsNotFatal pins the other half of the deployment
|
||||
// contract: a NOTIFY_SOCKET that cannot be written to is logged and ignored.
|
||||
// A daemon that refused to serve because systemd's socket was unavailable
|
||||
// would be a regression on every deployment that has no systemd at all.
|
||||
func TestNotifySocketFailureIsNotFatal(t *testing.T) {
|
||||
missing := filepath.Join(t.TempDir(), "absent", "n.sock")
|
||||
t.Setenv(sdnotify.NotifySocketEnv, missing)
|
||||
t.Setenv(sdnotify.WatchdogUsecEnv, "20000")
|
||||
|
||||
rec := ¬ifyRecorder{}
|
||||
b, d := newNotifyTestBoot(t, 50*time.Millisecond)
|
||||
b.log = slog.New(rec)
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
|
||||
var polling atomic.Bool
|
||||
polling.Store(true)
|
||||
go pollPasses(ctx, d, &polling, 5*time.Millisecond)
|
||||
|
||||
b.announceReady()
|
||||
b.startWatchdog(ctx)
|
||||
|
||||
if warns := rec.at(slog.LevelWarn); len(warns) != 1 {
|
||||
t.Errorf("announceReady against an unusable socket logged %d warnings, want exactly 1", len(warns))
|
||||
}
|
||||
|
||||
// The sampler keeps trying rather than dying on the first failure, so more
|
||||
// warnings arrive while the loop progresses.
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if len(rec.at(slog.LevelWarn)) > 1 {
|
||||
break
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
if warns := rec.at(slog.LevelWarn); len(warns) < 2 {
|
||||
t.Errorf("the watchdog logged %d warnings, want the heartbeat still being attempted", len(warns))
|
||||
}
|
||||
if errs := rec.at(slog.LevelError); len(errs) != 0 {
|
||||
t.Errorf("an unusable notify socket logged %d errors, want none: %v", len(errs), errs)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStateStoreBootAnnouncesReady: archie-state-store run as a Type=notify
|
||||
// unit must send READY=1 once its boot is over and it is serving the contract,
|
||||
// or systemd kills a healthy process once TimeoutStartSec expires
|
||||
// (archie-core-1174). The real RunStateStore composition drives it, over a
|
||||
// real State Store database, the way the provider-seeding boot test does.
|
||||
func TestStateStoreBootAnnouncesReady(t *testing.T) {
|
||||
listener := newNotifyListener(t)
|
||||
url := pgtest.URL(t)
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
body := fmt.Sprintf("bot_user = 'archie'\ndatabase_url = %q\n", url)
|
||||
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
errCh := make(chan error, 1)
|
||||
go func() { errCh <- RunStateStore(ctx, StateStoreOptions{Config: path, Listen: "127.0.0.1:0"}) }()
|
||||
|
||||
if !listener.waitForState(t, 15*time.Second, sdnotify.ReadyState) {
|
||||
select {
|
||||
case bootErr := <-errCh:
|
||||
t.Fatalf("RunStateStore exited before announcing ready: %v", bootErr)
|
||||
default:
|
||||
t.Fatal("no READY=1 datagram within 15s of boot")
|
||||
}
|
||||
}
|
||||
|
||||
cancel()
|
||||
if err := <-errCh; err != nil && !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("RunStateStore shutdown: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,284 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration/setup"
|
||||
)
|
||||
|
||||
func TestSetupSubcommandIsRecognised(t *testing.T) {
|
||||
if !IsSetupArgs([]string{setupCommand, "--defaults"}) {
|
||||
t.Errorf("IsSetupArgs() did not recognise %q", setupCommand)
|
||||
}
|
||||
if IsSetupArgs([]string{"-once"}) {
|
||||
t.Error("IsSetupArgs() claimed a normal daemon flag")
|
||||
}
|
||||
if IsSetupArgs(nil) {
|
||||
t.Error("IsSetupArgs() claimed an empty argument list")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunSetup_DefaultsWritesLoadableConfig(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfgPath := filepath.Join(dir, "config.toml")
|
||||
|
||||
stdin, err := os.Open(os.DevNull)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer stdin.Close()
|
||||
|
||||
var stdout, stderr strings.Builder
|
||||
code := RunSetup([]string{"--defaults", "-config", cfgPath}, stdin, &stdout, &stderr)
|
||||
if code != 0 {
|
||||
t.Fatalf("RunSetup exit = %d, stderr:\n%s", code, stderr.String())
|
||||
}
|
||||
|
||||
info, err := os.Stat(cfgPath)
|
||||
if err != nil {
|
||||
t.Fatalf("config not written: %v", err)
|
||||
}
|
||||
if info.Mode().Perm() != 0o600 {
|
||||
t.Errorf("config mode = %v, want 0600", info.Mode().Perm())
|
||||
}
|
||||
|
||||
doc, err := configuration.New(nil).File(cfgPath)
|
||||
if err != nil {
|
||||
t.Fatalf("generated config does not load: %v", err)
|
||||
}
|
||||
if doc.Config.BotUser != "archie-bot" {
|
||||
t.Errorf("bot_user = %q, want archie-bot", doc.Config.BotUser)
|
||||
}
|
||||
|
||||
// The defaults baseline is keyless (ollama), so nothing may be written
|
||||
// to the env file.
|
||||
if _, err := os.Stat(filepath.Join(dir, "env")); !os.IsNotExist(err) {
|
||||
t.Errorf("env file should not exist after a defaults run, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunSetupRejectsSecretValueFlags pins that no secret value can be passed
|
||||
// on the command line. Secrets are set in a secret engine; this flow only ever
|
||||
// writes a reference to one. A flag that carried a value would be a second,
|
||||
// silent way to set a secret -- and would put it in shell history and in every
|
||||
// process listing, which is why install.sh prompts with read_secret instead.
|
||||
func TestRunSetupRejectsSecretValueFlags(t *testing.T) {
|
||||
for _, flagName := range []string{"-forge-token", "-provider-api-key", "-telegram-token"} {
|
||||
t.Run(flagName, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfgPath := filepath.Join(dir, "config.toml")
|
||||
devNull, err := os.Open(os.DevNull)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = devNull.Close() }()
|
||||
|
||||
var stdout, stderr strings.Builder
|
||||
code := RunSetup([]string{"--defaults", "-config", cfgPath, flagName, "leaked-value"}, devNull, &stdout, &stderr)
|
||||
if code != 2 {
|
||||
t.Fatalf("RunSetup with %s = exit %d, want 2 (unknown flag); stderr: %s", flagName, code, stderr.String())
|
||||
}
|
||||
if _, err := os.Stat(cfgPath); !os.IsNotExist(err) {
|
||||
t.Errorf("config written despite a rejected flag: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "env")); !os.IsNotExist(err) {
|
||||
t.Errorf("env file written despite a rejected flag: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunSetup_GuidedRequiresTTY(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfgPath := filepath.Join(dir, "config.toml")
|
||||
|
||||
stdin, err := os.Open(os.DevNull)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer stdin.Close()
|
||||
|
||||
var stdout, stderr strings.Builder
|
||||
code := RunSetup([]string{"-config", cfgPath}, stdin, &stdout, &stderr)
|
||||
if code == 0 {
|
||||
t.Fatalf("RunSetup exit = 0, want non-zero for a guided run without a TTY")
|
||||
}
|
||||
if _, err := os.Stat(cfgPath); !os.IsNotExist(err) {
|
||||
t.Errorf("config should not be written when a guided non-TTY run is refused, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallValidatedConfig_ValidationFailureWritesNothing(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfgPath := filepath.Join(dir, "config.toml")
|
||||
sink := setup.NewEnvFileSink(filepath.Join(dir, "env"))
|
||||
if err := sink.Put("env", "ARCHIE_GITHUB_TOKEN", "secret"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err := installValidatedConfig(configuration.New(nil), cfgPath, sink, []byte("this is not toml"))
|
||||
if err == nil {
|
||||
t.Fatal("installValidatedConfig = nil error, want a load failure")
|
||||
}
|
||||
if _, err := os.Stat(cfgPath); !os.IsNotExist(err) {
|
||||
t.Errorf("config written despite validation failure: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "env")); !os.IsNotExist(err) {
|
||||
t.Errorf("secret written despite validation failure: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestInstallValidatedConfig_ConfigWriteFailureLeavesNoSecret pins the write
|
||||
// order the setup package's SecretSink contract depends on: the config is
|
||||
// installed before any secret is committed, so a secret is never left on disk
|
||||
// pointing at a config that was never written.
|
||||
//
|
||||
// This is not covered by the validation-failure test: inverting the two writes
|
||||
// leaves every other test in the package green, so this assertion is what
|
||||
// actually holds the invariant.
|
||||
func TestInstallValidatedConfig_ConfigWriteFailureLeavesNoSecret(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
// The parent directory does not exist, so validation succeeds and the
|
||||
// config write fails.
|
||||
cfgPath := filepath.Join(dir, "missing", "config.toml")
|
||||
envPath := filepath.Join(dir, "env")
|
||||
sink := setup.NewEnvFileSink(envPath)
|
||||
if err := sink.Put("env", "ARCHIE_GITHUB_TOKEN", "secret"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rendered := []byte("bot_user = \"widget\"\nwork_dir = \"/tmp/archie-setup-work\"\n")
|
||||
|
||||
// Prove the fixture is loadable BEFORE relying on the write failing.
|
||||
// Asserted by loading it rather than by matching the error text below: a
|
||||
// reworded error must not silently disarm this guard and let the test pass
|
||||
// for the wrong reason.
|
||||
fixture := filepath.Join(dir, "fixture.toml")
|
||||
if err := os.WriteFile(fixture, rendered, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := configuration.New(nil).File(fixture); err != nil {
|
||||
t.Fatalf("fixture config does not load, so this test would not exercise the write path: %v", err)
|
||||
}
|
||||
|
||||
if err := installValidatedConfig(configuration.New(nil), cfgPath, sink, rendered); err == nil {
|
||||
t.Fatal("installValidatedConfig = nil error, want a write failure")
|
||||
}
|
||||
if _, statErr := os.Stat(envPath); !os.IsNotExist(statErr) {
|
||||
t.Errorf("secret committed even though the config was never written: %v", statErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunSetup_SecretRefFlagsWriteReferencesWithoutEnvFile pins the reference
|
||||
// form end to end: naming where a secret is stored writes the reference, and
|
||||
// setup stores nothing, so no env file appears. The engine here (bws) is one
|
||||
// setup has no writer for -- which is the point, the value is not setup's.
|
||||
func TestRunSetup_SecretRefFlagsWriteReferencesWithoutEnvFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfgPath := filepath.Join(dir, "config.toml")
|
||||
devNull, err := os.Open(os.DevNull)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = devNull.Close() }()
|
||||
|
||||
var stdout, stderr strings.Builder
|
||||
code := RunSetup([]string{
|
||||
"--defaults", "-config", cfgPath,
|
||||
"-provider", "openai", "-model", "gpt-5.4",
|
||||
"-provider-secret-ref", "bws:OPENAI_API_KEY",
|
||||
"-forge-secret-ref", "bws:ARCHIE_GITHUB_TOKEN",
|
||||
}, devNull, &stdout, &stderr)
|
||||
if code != 0 {
|
||||
t.Fatalf("RunSetup exit = %d, stderr: %s", code, stderr.String())
|
||||
}
|
||||
|
||||
doc, err := configuration.New(nil).File(cfgPath)
|
||||
if err != nil {
|
||||
t.Fatalf("generated config does not load: %v", err)
|
||||
}
|
||||
if got, want := doc.Config.Providers["openai"].APIKey, (config.SecretRef{Engine: "bws", Key: "OPENAI_API_KEY"}); got != want {
|
||||
t.Errorf("providers.openai.api_key = %+v, want %+v", got, want)
|
||||
}
|
||||
if got, want := doc.Config.Forge.Token, (config.SecretRef{Engine: "bws", Key: "ARCHIE_GITHUB_TOKEN"}); got != want {
|
||||
t.Errorf("forge.token = %+v, want %+v", got, want)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "env")); !os.IsNotExist(err) {
|
||||
t.Errorf("env file written: a reference means setup stores no value (stat err: %v)", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunSetup_RejectsReferencesNothingWouldUse pins the no-silent-no-op rule.
|
||||
// A reference for a keyless provider, or for a disabled forge, would sit in the
|
||||
// config looking configured while nothing read it -- the failure shape this
|
||||
// whole flow exists to remove -- so it is refused instead.
|
||||
func TestRunSetup_RejectsReferencesNothingWouldUse(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
}{
|
||||
{name: "provider ref with the keyless self-hosted provider", args: []string{"-provider-secret-ref", "bws:OPENAI_API_KEY"}},
|
||||
{name: "forge ref with the forge disabled", args: []string{"-forge-type", "none", "-forge-secret-ref", "bws:ARCHIE_GITHUB_TOKEN"}},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfgPath := filepath.Join(dir, "config.toml")
|
||||
devNull, err := os.Open(os.DevNull)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = devNull.Close() }()
|
||||
|
||||
args := append([]string{"--defaults", "-config", cfgPath}, tc.args...)
|
||||
var stdout, stderr strings.Builder
|
||||
if code := RunSetup(args, devNull, &stdout, &stderr); code == 0 {
|
||||
t.Fatalf("RunSetup = exit 0, want a refusal; stderr: %s", stderr.String())
|
||||
}
|
||||
if _, err := os.Stat(cfgPath); !os.IsNotExist(err) {
|
||||
t.Errorf("config written despite the refusal: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunSetup_GeneratedConfigSatisfiesDaemonRequirements pins the properties
|
||||
// archied needs of whatever setup emits, asserted on the GENERATED config.
|
||||
//
|
||||
// It replaces a test that read config.example.toml and reconstructed install.sh's
|
||||
// shell heredoc. Testing hand-written files is testing an artifact a human or an
|
||||
// agent may legitimately rewrite at any time -- and that test in fact broke the
|
||||
// moment install.sh stopped generating config, because the heredoc it parsed no
|
||||
// longer existed. The generated output is the contract; the template is an input.
|
||||
func TestRunSetup_GeneratedConfigSatisfiesDaemonRequirements(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfgPath := filepath.Join(dir, "config.toml")
|
||||
devNull, err := os.Open(os.DevNull)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = devNull.Close() }()
|
||||
|
||||
var stdout, stderr strings.Builder
|
||||
if code := RunSetup([]string{"--defaults", "-config", cfgPath}, devNull, &stdout, &stderr); code != 0 {
|
||||
t.Fatalf("RunSetup exit = %d, stderr: %s", code, stderr.String())
|
||||
}
|
||||
|
||||
doc, err := configuration.New(nil).File(cfgPath)
|
||||
if err != nil {
|
||||
t.Fatalf("generated config does not load: %v", err)
|
||||
}
|
||||
// openStateStoreAdapter refuses an empty target, so this is the difference
|
||||
// between a config that boots and one that does not.
|
||||
if doc.Config.Services.Get(config.ServiceNameState).Target == "" {
|
||||
t.Error("generated config leaves services.state.target empty; the daemon would not boot")
|
||||
}
|
||||
if doc.Config.BotUser == "" {
|
||||
t.Error("generated config leaves bot_user empty")
|
||||
}
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// testWatchdogLeash is deliberately short so the watchdog tests are fast and
|
||||
// deterministic. The real production leash is drain timeout plus grace
|
||||
// period -- far longer than anything a unit test should wait for.
|
||||
const testWatchdogLeash = 30 * time.Millisecond
|
||||
|
||||
// testWatchdogExitTimeout bounds how long a test waits for the watchdog's
|
||||
// forced exit to be observed. It is deliberately generous: the leash only
|
||||
// starts the timer, and the firing goroutine must then be scheduled onto a
|
||||
// core before the injected exit is observable. A deadline of a few leash
|
||||
// lengths is a wall-clock race against the Go scheduler, and it fails
|
||||
// intermittently on a loaded machine -- the test then parks real work behind a
|
||||
// gate failure that has nothing to do with the change under test. The test
|
||||
// still completes in ~30ms; this is a ceiling, not a sleep.
|
||||
const testWatchdogExitTimeout = 5 * time.Second
|
||||
|
||||
// testWatchdogStandDownPeriod is the shorter wait used where the test asserts
|
||||
// the ABSENCE of a forced exit. Load cannot make that assertion lie: a slow
|
||||
// runner only delays the very exit the test is checking for, so a tight bound
|
||||
// is safe in this direction and keeps the suite fast. It still leaves the
|
||||
// leash many times over for a broken disarm to reveal itself, which is the
|
||||
// regression this half of the pair exists to catch.
|
||||
const testWatchdogStandDownPeriod = testWatchdogLeash * 10
|
||||
|
||||
func discardWatchdogLogger() *slog.Logger {
|
||||
return slog.New(slog.DiscardHandler)
|
||||
}
|
||||
|
||||
// TestShutdownWatchdogHangingPastLeashForcesExit proves the backstop: once
|
||||
// graceful shutdown begins and never completes (the shutdown machinery is
|
||||
// hung, so the disarm is never called), the watchdog force-exits the process
|
||||
// after the leash expires.
|
||||
//
|
||||
// The timing contract asserted here is the one that actually matters and the
|
||||
// one scheduling jitter cannot falsify: the exit must NOT happen before the
|
||||
// leash, and it must happen. Waiting for it with a generous ceiling keeps the
|
||||
// second half honest under load; asserting elapsed >= leash keeps the first
|
||||
// half strict, because delaying the goroutine only ever makes it later, never
|
||||
// earlier.
|
||||
func TestShutdownWatchdogHangingPastLeashForcesExit(t *testing.T) {
|
||||
exited := make(chan int, 1)
|
||||
w := newShutdownWatchdog(testWatchdogLeash, discardWatchdogLogger())
|
||||
w.exit = func(code int) { exited <- code }
|
||||
|
||||
began := make(chan struct{})
|
||||
_ = w.watch(began)
|
||||
|
||||
// Graceful shutdown begins and never completes: no disarm is called.
|
||||
start := time.Now()
|
||||
close(began)
|
||||
|
||||
select {
|
||||
case code := <-exited:
|
||||
if code != 1 {
|
||||
t.Fatalf("watchdog force-exited with code %d, want 1", code)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed < testWatchdogLeash {
|
||||
t.Fatalf("watchdog force-exited after %s, before the %s leash had expired", elapsed, testWatchdogLeash)
|
||||
}
|
||||
case <-time.After(testWatchdogExitTimeout):
|
||||
t.Fatalf("watchdog did not force-exit within %s (leash %s)", testWatchdogExitTimeout, testWatchdogLeash)
|
||||
}
|
||||
}
|
||||
|
||||
// TestShutdownWatchdogCompletingWithinLeashDoesNotExit proves the inverse:
|
||||
// a shutdown that completes within the leash (the disarm is called before the
|
||||
// leash expires) does not trigger the watchdog.
|
||||
//
|
||||
// The disarm closes the watchdog's done channel, so the goroutine stands down
|
||||
// and no exit can follow. This asserts the ABSENCE of a forced exit, which is
|
||||
// the direction load cannot falsify -- a slow runner only delays the exit
|
||||
// being checked for -- so a tight bound is both safe and honest here.
|
||||
func TestShutdownWatchdogCompletingWithinLeashDoesNotExit(t *testing.T) {
|
||||
exited := make(chan int, 1)
|
||||
w := newShutdownWatchdog(testWatchdogLeash, discardWatchdogLogger())
|
||||
w.exit = func(code int) { exited <- code }
|
||||
|
||||
began := make(chan struct{})
|
||||
disarm := w.watch(began)
|
||||
|
||||
// Shutdown begins and completes immediately, well within the leash.
|
||||
close(began)
|
||||
disarm()
|
||||
|
||||
select {
|
||||
case code := <-exited:
|
||||
t.Fatalf("watchdog force-exited with code %d despite completing within leash", code)
|
||||
case <-time.After(testWatchdogStandDownPeriod):
|
||||
// Correct: a shutdown that completed within the leash did not
|
||||
// trigger the forced exit.
|
||||
}
|
||||
}
|
||||
|
||||
// TestBootStartShutdownWatchdogDisarmRunsLast pins the wiring invariant that
|
||||
// makes the backstop sound: the disarm the watchdog registers must be the
|
||||
// FIRST cleanup so it runs LAST in the LIFO shutdown chain. If it were
|
||||
// registered after a subsystem's cleanup, a hung subsystem would let the
|
||||
// disarm run early and the watchdog would stand down before the backstop was
|
||||
// needed.
|
||||
func TestBootStartShutdownWatchdogDisarmRunsLast(t *testing.T) {
|
||||
b := newBootstrap()
|
||||
ctx := t.Context()
|
||||
b.startShutdownWatchdog(ctx)
|
||||
|
||||
if len(b.cleanups) != 1 {
|
||||
t.Fatalf("startShutdownWatchdog registered %d cleanups, want exactly the disarm", len(b.cleanups))
|
||||
}
|
||||
|
||||
// A later subsystem's shutdown cleanup is appended after the disarm, so in
|
||||
// the LIFO chain it runs BEFORE the disarm.
|
||||
var ran []string
|
||||
b.addCleanup(func() { ran = append(ran, "subsystem") })
|
||||
b.cleanup()
|
||||
|
||||
if len(ran) != 1 || ran[0] != "subsystem" {
|
||||
t.Fatalf("cleanup order = %v, want the disarm to run after the subsystem cleanup", ran)
|
||||
}
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
func TestComposeStateStoreClientRequiresTarget(t *testing.T) {
|
||||
_, _, err := composeStateStoreClient(config.Services{}, &secret.Registry{})
|
||||
if err == nil {
|
||||
t.Fatal("empty target should error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "services.state.target is required") {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestComposeStateStoreClientNonLoopbackFailsClosed(t *testing.T) {
|
||||
// Keep this test independent of credentials inherited from the test runner.
|
||||
t.Setenv("STATE_STORE_TOKEN", "")
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
target string
|
||||
}{
|
||||
{name: "wildcard without token", target: "0.0.0.0:9090"},
|
||||
{name: "hostname without token", target: "store.example.com:9090"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
_, _, err := composeStateStoreClient(config.Services{config.ServiceNameState: {Target: tt.target}}, &secret.Registry{})
|
||||
if err == nil {
|
||||
t.Fatalf("non-loopback %q without a token should fail closed (docs/prds/state-store-contract.md §9)", tt.target)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestComposeStateStoreClientLoopbackSucceeds(t *testing.T) {
|
||||
st, cleanup, err := composeStateStoreClient(config.Services{config.ServiceNameState: {Target: "127.0.0.1:9090"}}, &secret.Registry{})
|
||||
if err != nil {
|
||||
t.Fatalf("loopback without token should succeed: %v", err)
|
||||
}
|
||||
if st == nil {
|
||||
t.Fatal("expected a non-nil store adapter")
|
||||
}
|
||||
if cleanup == nil {
|
||||
t.Fatal("expected a cleanup func")
|
||||
}
|
||||
cleanup() // must not panic or fail; Close() on the adapter is a no-op (§11)
|
||||
}
|
||||
|
||||
func TestComposeStateStoreClientTokenFromTargetToken(t *testing.T) {
|
||||
// Non-loopback with a configured token must not fail closed; the interceptor
|
||||
// is what carries it, so the client is dialable.
|
||||
st, _, err := composeStateStoreClient(config.Services{config.ServiceNameState: {Target: "0.0.0.0:9090", TargetToken: "secret"}}, &secret.Registry{})
|
||||
if err != nil {
|
||||
t.Fatalf("non-loopback with a token should succeed: %v", err)
|
||||
}
|
||||
if st == nil {
|
||||
t.Fatal("expected a non-nil store adapter")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenStateStoreAdapterRequiresTarget(t *testing.T) {
|
||||
b := newBootstrap()
|
||||
b.secrets = &secret.Registry{}
|
||||
// After .4.6 the daemon and gateway no longer own archie.db in-process, so
|
||||
// an empty [services.state].target is a composition error, not the old
|
||||
// local task-store default (docs/prds/state-store-contract.md §12 step 7).
|
||||
if err := b.openStateStoreAdapter(); err == nil {
|
||||
t.Fatal("empty services.state.target should error: the in-process store path is deleted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenStateStoreAdapterRemoteFailsClosed(t *testing.T) {
|
||||
// Keep this test independent of credentials inherited from the test runner.
|
||||
t.Setenv("STATE_STORE_TOKEN", "")
|
||||
b := newBootstrap()
|
||||
b.secrets = &secret.Registry{}
|
||||
b.cfg.Services = config.Services{config.ServiceNameState: {Target: "0.0.0.0:9090"}}
|
||||
if err := b.openStateStoreAdapter(); err == nil {
|
||||
t.Fatal("non-loopback without a token should fail closed")
|
||||
}
|
||||
}
|
||||
|
||||
// TestStateStoreSingleOwnerComposition proves the single-owner SQLite
|
||||
// invariant at the composition root: both production consumers (the daemon
|
||||
// Run path and the gateway RunGateway) resolve their task-store surface from
|
||||
// openStateStoreAdapter, which REQUIRES [services.state].target and never
|
||||
// opens archie.db directly. After .4.6 the in-process store path is deleted
|
||||
// (docs/prds/state-store-contract.md §12 step 7), so an empty target is a
|
||||
// startup error rather than the old local default -- if it were not, the
|
||||
// daemon or gateway would open the single SQLite file behind the store
|
||||
// service's back, violating no-dual-store-ownership.
|
||||
func TestStateStoreSingleOwnerComposition(t *testing.T) {
|
||||
b := newBootstrap()
|
||||
b.secrets = &secret.Registry{}
|
||||
|
||||
// The daemon openStores path must not construct a local task store.
|
||||
// openStores only resolves secrets and the forge client, then opens chat
|
||||
// sessions; the task store surface comes from the remote adapter, so no
|
||||
// archie.db task file is touched. This asserts openStateStoreAdapter (the
|
||||
// only task-store constructor) rejects an empty target.
|
||||
if err := b.openStateStoreAdapter(); err == nil {
|
||||
t.Fatal("empty services.state.target must error: the in-process store path is deleted (single owner = archie-state-store)")
|
||||
}
|
||||
if b.stateStore != nil {
|
||||
t.Fatalf("stateStore = %p, want nil (no local store opened)", b.stateStore)
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
taskactionstore "github.com/samcharles93/archie-core/internal/infrastructure/taskactions"
|
||||
)
|
||||
|
||||
// openSecondStore opens a second, independent *pgstore.TaskDB on a fresh temp
|
||||
// path so a boot consumer test can prove the composition routes through
|
||||
// b.stateStore rather than b.st: the two differ by identity, so an assertion
|
||||
// that a consumer field holds storeB (not storeA) can only pass if the wiring
|
||||
// reads b.stateStore.
|
||||
// stateStoreAdapter stands in for the real adapter (*staterpc.Client), which
|
||||
// fronts both halves of the contract over one connection: the task store and
|
||||
// the event-capture store. A plain *pgstore.TaskDB no longer satisfies the
|
||||
// event-capture surfaces, so a test that asserts "everything routes through
|
||||
// the adapter" needs something that implements them, exactly as the client
|
||||
// does in production.
|
||||
type stateStoreAdapter struct {
|
||||
*pgstore.TaskDB
|
||||
*postgres.EDA
|
||||
}
|
||||
|
||||
func openSecondStore(t *testing.T) *stateStoreAdapter {
|
||||
t.Helper()
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
return &stateStoreAdapter{TaskDB: st, EDA: pgstore.EDA(t, nil)}
|
||||
}
|
||||
|
||||
// TestBuildDaemonRoutesTaskStoreThroughStateStore proves the daemon's task
|
||||
// lifecycle consumer resolves its store surfaces from b.stateStore (the State
|
||||
// Store contract adapter -- always the remote *staterpc.Client after .4.6)
|
||||
// and not from b.st directly. This is the .4.5 TaskStore-composite swap
|
||||
// (docs/prds/state-store-contract.md §12 step 6): the daemon's Store field and
|
||||
// its mapping/binding dispatch surfaces all come from the adapter.
|
||||
func TestBuildDaemonRoutesTaskStoreThroughStateStore(t *testing.T) {
|
||||
storeA := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = storeA.Close() })
|
||||
storeB := openSecondStore(t)
|
||||
|
||||
b := &boot{
|
||||
cfg: config.Config{},
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
st: storeA,
|
||||
stateStore: storeB,
|
||||
}
|
||||
b.buildDaemon()
|
||||
|
||||
if b.d.Store != storeB {
|
||||
t.Fatalf("daemon Store = %p, want b.stateStore (%p); task lifecycle did not route through the State Store adapter", b.d.Store, storeB)
|
||||
}
|
||||
if b.d.Mappings != storeB {
|
||||
t.Fatalf("daemon Mappings = %p, want b.stateStore (%p)", b.d.Mappings, storeB)
|
||||
}
|
||||
if b.d.Bindings != storeB {
|
||||
t.Fatalf("daemon Bindings = %p, want b.stateStore (%p)", b.d.Bindings, storeB)
|
||||
}
|
||||
if b.d.BindingDispatcher != storeB {
|
||||
t.Fatalf("daemon BindingDispatcher = %p, want b.stateStore (%p)", b.d.BindingDispatcher, storeB)
|
||||
}
|
||||
if b.d.BindingTaskCreator != storeB {
|
||||
t.Fatalf("daemon BindingTaskCreator = %p, want b.stateStore (%p)", b.d.BindingTaskCreator, storeB)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskActionsRoutesThroughStateStore proves the daemon's operator task
|
||||
// action service wraps b.stateStore (the contract adapter), so an operator
|
||||
// approve/cancel/archive action mutates the same store the daemon lifecycle
|
||||
// uses.
|
||||
func TestTaskActionsRoutesThroughStateStore(t *testing.T) {
|
||||
storeB := openSecondStore(t)
|
||||
|
||||
b := &boot{
|
||||
cfg: config.Config{},
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
stateStore: storeB,
|
||||
}
|
||||
svc := b.taskActions()
|
||||
shadow, ok := svc.Store.(taskactionstore.Store)
|
||||
if !ok {
|
||||
t.Fatalf("taskactions Service.Store = %T, want taskactionstore.Store", svc.Store)
|
||||
}
|
||||
if shadow.TaskStore != storeB {
|
||||
t.Fatalf("taskactions TaskStore = %p, want b.stateStore (%p)", shadow.TaskStore, storeB)
|
||||
}
|
||||
}
|
||||
@@ -1,243 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
)
|
||||
|
||||
// keepaliveDialerMargin is the headroom the enforcement floor keeps under the
|
||||
// dialer's ping interval: the floor is half that interval, so a ping lands a
|
||||
// factor of two clear of a strike rather than on the boundary.
|
||||
const keepaliveDialerMargin = 2
|
||||
|
||||
// TestStateStoreServerOptsHoldTheDialersKeepaliveMargin is the cheap half of
|
||||
// the keepalive guard, and the only half that runs when someone changes the
|
||||
// policy: it asserts in microseconds what the stream case below proves over the
|
||||
// control's tear-down time (measured: 41.0s), so a server half that stops
|
||||
// tolerating the dialer's pings fails immediately instead of at the end of a
|
||||
// 50s window.
|
||||
//
|
||||
// A grpc.ServerOption is a closure over unexported grpc state, so neither the
|
||||
// option stateStoreServerOpts returns nor the one ServerKeepaliveOption builds
|
||||
// can be read back once built. What is asserted is therefore the two facts the
|
||||
// chain is made of: the shape of the option list (a loopback listener installs
|
||||
// exactly one, the enforcement policy, and nothing else) and the value that
|
||||
// option is built from, staterpc.ServerKeepalivePolicy. Both numbers in the
|
||||
// agreement are read from staterpc, the package that dials the client and
|
||||
// serves the option, so no assertion here restates a value one of the halves
|
||||
// owns.
|
||||
func TestStateStoreServerOptsHoldTheDialersKeepaliveMargin(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
opts, loopback, err := stateStoreServerOpts("127.0.0.1:9090", "", &staterpc.TaskGrants{})
|
||||
if err != nil {
|
||||
t.Fatalf("stateStoreServerOpts: %v", err)
|
||||
}
|
||||
if !loopback {
|
||||
t.Fatal("127.0.0.1 must be reported as loopback")
|
||||
}
|
||||
// The token interceptors belong to the non-loopback branch, so exactly one
|
||||
// option here is the enforcement policy and nothing else: fewer means the
|
||||
// server serves grpc's default policy (MinTime 5m), which answers the
|
||||
// dialer's pings with GOAWAY too_many_pings and tears a quiet watch down at
|
||||
// ~41s.
|
||||
if len(opts) != 1 {
|
||||
t.Fatalf("the loopback listener installs %d server options, want 1 (the keepalive enforcement policy)", len(opts))
|
||||
}
|
||||
|
||||
floor := staterpc.ServerKeepalivePolicy()
|
||||
dialer := staterpc.ClientKeepaliveParams()
|
||||
|
||||
if floor.MinTime != 5*time.Second {
|
||||
t.Fatalf("the enforcement floor is %s, want 5s: grpc's default 5m is the defect itself, and 10s would sit on the dialer's own KeepaliveMinPingTime clamp, where a ping a microsecond early is a strike", floor.MinTime)
|
||||
}
|
||||
if floor.PermitWithoutStream {
|
||||
t.Fatal("PermitWithoutStream = true: the dialer never pings a connection with no streams, so permitting them only relaxes a setting nothing exercises -- and a streamless ping from any other client would draw strikes against the dialer's traffic")
|
||||
}
|
||||
|
||||
// The relationship, not the literal, is what makes the pair correct: the
|
||||
// dialer's keepalive loop arms its timer one Time ahead and re-arms only
|
||||
// later (on read activity), so consecutive pings are never closer than Time
|
||||
// apart. A floor below that interval is never reached; a floor equal to it
|
||||
// is reached by any ping that arrives early.
|
||||
if floor.MinTime >= dialer.Time {
|
||||
t.Fatalf("the enforcement floor %s is not below the dialer's %s ping interval: every ping would land on the strike boundary", floor.MinTime, dialer.Time)
|
||||
}
|
||||
if floor.MinTime*keepaliveDialerMargin > dialer.Time {
|
||||
t.Fatalf("the enforcement floor %s must be at most %s (a %dx margin under the dialer's %s ping interval): the margin is what a loaded machine's timer delay eats before a ping draws a strike", floor.MinTime, dialer.Time/keepaliveDialerMargin, keepaliveDialerMargin, dialer.Time)
|
||||
}
|
||||
}
|
||||
|
||||
// keepaliveWindow is how long each case below holds one control-plane watch
|
||||
// open. It has to outlast the point where grpc's default enforcement policy
|
||||
// tears the link down: the dialer pings every 10s (staterpc's client keepalive
|
||||
// time, which is also grpc's KeepaliveMinPingTime floor, so a client cannot
|
||||
// ping sooner), the default EnforcementPolicy.MinTime is 5 minutes, and the
|
||||
// server sends GOAWAY too_many_pings once the strikes pass 2 (maxPingStrikes).
|
||||
// Measured: the connection dies 41.0s into the stream. The remaining ~9s are
|
||||
// there because a loaded machine delays timers, which can only move that
|
||||
// tear-down later.
|
||||
const keepaliveWindow = 50 * time.Second
|
||||
|
||||
// TestStateStoreServerOptionsTolerateTheDialersKeepalive holds one watch open
|
||||
// against two servers: one with grpc's default enforcement policy, one with the
|
||||
// options the State Store process actually serves with. The default policy is
|
||||
// the defect -- a server that counts every one of the dialer's pings as a
|
||||
// strike tears down a connection that carries no traffic for ~40s, and a watch
|
||||
// is silent by design while the watched resource's version is unchanged
|
||||
// (internal/app/controlplane's Watch; the dashboard holds the same shape over
|
||||
// its own connection in internal/webui/api_control_plane.go, writing nothing
|
||||
// between versions). That case is also what keeps the other one honest: a
|
||||
// policy that never strikes has nothing to tear down.
|
||||
//
|
||||
// The pair's cases run concurrently (t.Parallel) and share no state: each has
|
||||
// its own bufconn listener, grpc.Server, dialed client and deadline, and each
|
||||
// asserts only on its own stream, so neither one's timing depends on the
|
||||
// other's scheduling. TestStateStoreServerOptsHoldTheDialersKeepaliveMargin
|
||||
// above pins the same agreement in microseconds; this case is the end-to-end
|
||||
// proof, which is the part a value assertion cannot give.
|
||||
func TestStateStoreServerOptionsTolerateTheDialersKeepalive(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skipf("holds a watch open for %s of wall clock; runs in the full suite (task test:full)", keepaliveWindow)
|
||||
}
|
||||
// The options the standalone State Store serves its local profile with,
|
||||
// taken from the composition rather than hand-built here.
|
||||
served, loopback, err := stateStoreServerOpts("127.0.0.1:9090", "", &staterpc.TaskGrants{})
|
||||
if err != nil {
|
||||
t.Fatalf("stateStoreServerOpts: %v", err)
|
||||
}
|
||||
if !loopback {
|
||||
t.Fatal("127.0.0.1 must be reported as loopback")
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
opts []grpc.ServerOption
|
||||
tornDown bool
|
||||
}{
|
||||
{
|
||||
// The control: without an enforcement policy coherent with the
|
||||
// dialer, the same client on the same stream dies mid-window.
|
||||
name: "grpc's default enforcement policy tears the dialer's watch down",
|
||||
tornDown: true,
|
||||
},
|
||||
{
|
||||
name: "the state store's server options keep the dialer's watch up",
|
||||
opts: served,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
elapsed, recvErr, survived := holdWatch(t, tc.opts, keepaliveWindow)
|
||||
// The server never writes, so the stream can only end because the
|
||||
// connection was torn down under it, or because it outlived the window.
|
||||
// Which one happened is the select in holdWatch, not the error the
|
||||
// window's closure surfaces: see holdWatch for why reading the error
|
||||
// made this case flaky.
|
||||
t.Logf("watch lasted %s, survived the window: %v, ended with %v", elapsed, survived, recvErr)
|
||||
if survived {
|
||||
if tc.tornDown {
|
||||
t.Fatalf("the dialer's watch was still open after %s: the default EnforcementPolicy (MinTime 5m) must strike pings that arrive 10s apart and answer with GOAWAY too_many_pings, so this case is not reaching the strike budget and the case below would prove nothing", keepaliveWindow)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !tc.tornDown {
|
||||
t.Fatalf("the dialer's watch ended after %s: %v\nA watch carrying no traffic must survive on the pings staterpc.Dial sends; a server policy that strikes them answers a quiet connection with a dead one at ~40s, which is worse than the keepalive it was added for", elapsed, recvErr)
|
||||
}
|
||||
if !strings.Contains(recvErr.Error(), "too_many_pings") {
|
||||
t.Fatalf("the dialer's watch ended after %s with %v: want GOAWAY too_many_pings, not some other connection loss", elapsed, recvErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// quietWatch is the server half of a control-plane watch that never writes: it
|
||||
// holds one stream open and sends nothing, the state a watch is in while the
|
||||
// watched resource's version is unchanged.
|
||||
type quietWatch struct {
|
||||
controlpb.UnimplementedControlPlaneServiceServer
|
||||
started chan struct{}
|
||||
}
|
||||
|
||||
func (w *quietWatch) Watch(_ *controlpb.WatchRequest, stream controlpb.ControlPlaneService_WatchServer) error {
|
||||
close(w.started)
|
||||
<-stream.Context().Done()
|
||||
return stream.Context().Err()
|
||||
}
|
||||
|
||||
// keepaliveSlack keeps the stream's own deadline clear of the observation window.
|
||||
// They must not be the same duration. The question holdWatch answers is whether
|
||||
// the link outlives the window, and with the two identical the client deadline
|
||||
// resolves microseconds after the timer either way: Recv returns
|
||||
// DeadlineExceeded and the answer becomes a race between two timers rather than
|
||||
// a fact about the link. Measured -- the same 50s window reported the healthy
|
||||
// case as "ended" at 49.998s while the timer was still pending.
|
||||
const keepaliveSlack = 5 * time.Second
|
||||
|
||||
// holdWatch serves opts over bufconn, dials it with the shipped dialer
|
||||
// (staterpc.Dial, so the client keepalive is exactly the one the daemon, the
|
||||
// dashboard and the agent container run), holds one watch stream open for
|
||||
// window, and reports how long the stream lasted, how it ended, and whether it
|
||||
// outlived the window.
|
||||
//
|
||||
// That last report is the property under test, and it is decided by which arm of
|
||||
// a select wins rather than by the flavour of the error the window's closure
|
||||
// surfaces. Reading the error instead -- asking for DeadlineExceeded -- made the
|
||||
// tolerant case flaky under load: the client deadline, the server's stream
|
||||
// context and the transport all resolve within microseconds of one another, so a
|
||||
// watch that was still perfectly open was reported as Canceled or Unavailable,
|
||||
// and a healthy link failed a test about unhealthy links. Measured on a loaded
|
||||
// 16-core host at 49.999s into a 50s window.
|
||||
func holdWatch(t *testing.T, opts []grpc.ServerOption, window time.Duration) (time.Duration, error, bool) {
|
||||
t.Helper()
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
watch := &quietWatch{started: make(chan struct{})}
|
||||
server := grpc.NewServer(opts...)
|
||||
controlpb.RegisterControlPlaneServiceServer(server, watch)
|
||||
served := make(chan struct{})
|
||||
go func() {
|
||||
defer close(served)
|
||||
_ = server.Serve(listener)
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
server.Stop()
|
||||
_ = listener.Close()
|
||||
<-served
|
||||
})
|
||||
|
||||
client := dialStateStore(t, listener, restartAdminToken)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), window+keepaliveSlack)
|
||||
defer cancel()
|
||||
stream, err := client.ControlPlane().Watch(ctx, &controlpb.WatchRequest{Kind: "any"})
|
||||
if err != nil {
|
||||
t.Fatalf("open watch: %v", err)
|
||||
}
|
||||
select {
|
||||
case <-watch.started:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("the server never started the watch stream")
|
||||
}
|
||||
start := time.Now()
|
||||
// Buffered so the receiving goroutine cannot outlive the call: cancel runs on
|
||||
// the way out, Recv returns, and the send still has somewhere to land.
|
||||
recv := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := stream.Recv()
|
||||
recv <- err
|
||||
}()
|
||||
select {
|
||||
case err := <-recv:
|
||||
return time.Since(start), err, false
|
||||
case <-time.After(window):
|
||||
return time.Since(start), nil, true
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
// TestOpenStateStorePoolFailsClosedWithoutURL pins D1.2: the State Store is
|
||||
// Postgres-only, so a missing database_url must stop it from starting rather
|
||||
// than fall back to SQLite.
|
||||
func TestOpenStateStorePoolFailsClosedWithoutURL(t *testing.T) {
|
||||
b := newBootstrap()
|
||||
b.cfg = config.Config{}
|
||||
if err := b.openStateStorePool(t.Context()); err == nil {
|
||||
t.Fatal("openStateStorePool without database_url succeeded; want fail closed")
|
||||
} else if !strings.Contains(err.Error(), "database_url is required") {
|
||||
t.Fatalf("openStateStorePool error = %v, want it to name the missing database_url", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenStateStorePoolFailsClosedOnInvalidURL pins the invalid half of D1.2:
|
||||
// a URL that will not connect (here, one that does not parse) is the same
|
||||
// failure as an absent one, surfaced at boot rather than at first query.
|
||||
func TestOpenStateStorePoolFailsClosedOnInvalidURL(t *testing.T) {
|
||||
b := newBootstrap()
|
||||
b.cfg = config.Config{DatabaseURL: "://not-a-url"}
|
||||
if err := b.openStateStorePool(t.Context()); err == nil {
|
||||
t.Fatal("openStateStorePool with an unparseable database_url succeeded; want fail closed")
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenStateStorePoolRefusesASecondOwner pins the serve-ownership claim: a
|
||||
// second State Store against the same database fails to start while the first
|
||||
// holds it, and starts once the first has shut down.
|
||||
func TestOpenStateStorePoolRefusesASecondOwner(t *testing.T) {
|
||||
url := pgtest.URL(t)
|
||||
first := newBootstrap()
|
||||
first.cfg = config.Config{DatabaseURL: url}
|
||||
if err := first.openStateStorePool(t.Context()); err != nil {
|
||||
t.Fatalf("first openStateStorePool: %v", err)
|
||||
}
|
||||
second := newBootstrap()
|
||||
second.cfg = config.Config{DatabaseURL: url}
|
||||
err := second.openStateStorePool(t.Context())
|
||||
second.cleanup()
|
||||
first.cleanup()
|
||||
if !errors.Is(err, postgres.ErrOwned) {
|
||||
t.Fatalf("second openStateStorePool = %v, want ErrOwned", err)
|
||||
}
|
||||
third := newBootstrap()
|
||||
third.cfg = config.Config{DatabaseURL: url}
|
||||
if err := third.openStateStorePool(t.Context()); err != nil {
|
||||
t.Fatalf("openStateStorePool after the owner shut down: %v", err)
|
||||
}
|
||||
third.cleanup()
|
||||
}
|
||||
@@ -1,202 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
// pgRecoveryFixture is a migrated database and the config file naming it,
|
||||
// which is all the Postgres recovery path is given: it resolves database_url
|
||||
// from the configuration exactly as the State Store does.
|
||||
func pgRecoveryFixture(t *testing.T) (configPath string, pool *pgxpool.Pool, url string) {
|
||||
t.Helper()
|
||||
url = pgtest.URL(t)
|
||||
dir := t.TempDir()
|
||||
configPath = filepath.Join(dir, "config.toml")
|
||||
body := fmt.Sprintf("bot_user = 'archie'\ndatabase_url = %q\n[forge]\ntype = 'github'\nhost = 'https://github.example.com'\n",
|
||||
url)
|
||||
if err := os.WriteFile(configPath, []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pool, err := postgres.Open(t.Context(), url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
if err := postgres.Migrate(t.Context(), pool, postgres.Migrations()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return configPath, pool, url
|
||||
}
|
||||
|
||||
func requirePGTools(t *testing.T) {
|
||||
t.Helper()
|
||||
for _, tool := range []string{"pg_dump", "pg_restore"} {
|
||||
if _, err := exec.LookPath(tool); err != nil {
|
||||
t.Skipf("%s is not on PATH; this test needs the PostgreSQL 18 client tools", tool)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func putResource(t *testing.T, pool *pgxpool.Pool, kind, value, label string) {
|
||||
t.Helper()
|
||||
resources := postgres.NewResources(pool)
|
||||
expected := int64(0)
|
||||
if current, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, kind); err == nil {
|
||||
expected = current.Version
|
||||
}
|
||||
if _, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: kind, Value: []byte(value), Actor: label, Source: "test",
|
||||
RequestID: fmt.Sprintf("%s-%d", label, expected+1), ExpectedVersion: expected,
|
||||
}); err != nil {
|
||||
t.Fatalf("put %s: %v", kind, err)
|
||||
}
|
||||
}
|
||||
|
||||
func holdRole(t *testing.T, url, role string) {
|
||||
t.Helper()
|
||||
pool, err := postgres.Open(t.Context(), url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
claim, err := postgres.AcquireOwnership(t.Context(), pool, role)
|
||||
if err != nil {
|
||||
t.Fatalf("hold %s: %v", role, err)
|
||||
}
|
||||
t.Cleanup(func() { _ = claim.Release(t.Context()) })
|
||||
}
|
||||
|
||||
func TestPostgresRecoveryRequiresADatabaseURL(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
configPath := filepath.Join(dir, "config.toml")
|
||||
if err := os.WriteFile(configPath, []byte("bot_user = 'archie'\n[forge]\ntype = 'github'\nhost = 'https://github.example.com'\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, op := range []string{RecoveryBackup, RecoveryRestore, RecoveryValidate, RecoveryRollback} {
|
||||
t.Run(op, func(t *testing.T) {
|
||||
_, err := RunStateStoreRecovery(t.Context(), StateStoreRecoveryOptions{
|
||||
Operation: op, Config: configPath, Out: filepath.Join(dir, "o"), From: filepath.Join(dir, "f"), Kind: "k",
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "database_url") {
|
||||
t.Fatalf("%s without database_url = %v, want a refusal naming database_url", op, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresRecoveryBackupAndRestore(t *testing.T) {
|
||||
requirePGTools(t)
|
||||
configPath, pool, url := pgRecoveryFixture(t)
|
||||
putResource(t, pool, controlplane.ModelRoleAssignmentsKind, `{"implement":"anthropic/claude"}`, "snapshot")
|
||||
snapshot := filepath.Join(t.TempDir(), "snapshot.dump")
|
||||
|
||||
if _, err := RunStateStoreRecovery(t.Context(), StateStoreRecoveryOptions{Operation: RecoveryBackup, Config: configPath, Out: snapshot}); err != nil {
|
||||
t.Fatalf("backup: %v", err)
|
||||
}
|
||||
putResource(t, pool, controlplane.ModelRoleAssignmentsKind, `{"implement":"openai/gpt"}`, "later")
|
||||
|
||||
for _, role := range postgres.ServiceOwners {
|
||||
t.Run("refused while "+role+" serves", func(t *testing.T) {
|
||||
holdRole(t, url, role)
|
||||
_, err := RunStateStoreRecovery(t.Context(), StateStoreRecoveryOptions{Operation: RecoveryRestore, Config: configPath, From: snapshot})
|
||||
if !errors.Is(err, postgres.ErrOwned) {
|
||||
t.Fatalf("restore with %s serving = %v, want ErrOwned", role, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
summary, err := RunStateStoreRecovery(t.Context(), StateStoreRecoveryOptions{Operation: RecoveryRestore, Config: configPath, From: snapshot})
|
||||
if err != nil {
|
||||
t.Fatalf("restore: %v", err)
|
||||
}
|
||||
if !strings.Contains(summary, "after the snapshot") {
|
||||
t.Errorf("restore must say writes after the snapshot are lost; summary = %q", summary)
|
||||
}
|
||||
current, err := postgres.NewResources(pool).Resource(t.Context(), storecontract.DefaultOrgID, controlplane.ModelRoleAssignmentsKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if current.Version != 1 {
|
||||
t.Errorf("restored version = %d, want the snapshot's 1", current.Version)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresRecoveryValidate(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
setup func(t *testing.T, pool *pgxpool.Pool)
|
||||
wantErr string
|
||||
}{
|
||||
{name: "healthy store", setup: func(*testing.T, *pgxpool.Pool) {}},
|
||||
{name: "schema newer than this binary", wantErr: "newer than this binary", setup: func(t *testing.T, pool *pgxpool.Pool) {
|
||||
if _, err := pool.Exec(t.Context(), "INSERT INTO goose_db_version (version_id, is_applied) VALUES ($1, true)", postgres.SupportedSchemaVersion()+1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}},
|
||||
{name: "stored value boot refuses", wantErr: "dispatch.trigger", setup: func(t *testing.T, pool *pgxpool.Pool) {
|
||||
putResource(t, pool, "scheduling-policy", `{"poll_interval":"1m","max_retries":3,"dispatch":{"trigger":"bogus"}}`, "bad")
|
||||
}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
configPath, pool, _ := pgRecoveryFixture(t)
|
||||
tt.setup(t, pool)
|
||||
summary, err := RunStateStoreRecovery(t.Context(), StateStoreRecoveryOptions{Operation: RecoveryValidate, Config: configPath})
|
||||
if tt.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("validate: %v", err)
|
||||
}
|
||||
if !strings.Contains(summary, fmt.Sprintf("schema version %d", postgres.SupportedSchemaVersion())) {
|
||||
t.Errorf("summary = %q, want the schema version", summary)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("validate = %v, want refusal containing %q", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresRecoveryRollback(t *testing.T) {
|
||||
configPath, pool, url := pgRecoveryFixture(t)
|
||||
kind := controlplane.ModelRoleAssignmentsKind
|
||||
putResource(t, pool, kind, `{"implement":"anthropic/claude"}`, "first")
|
||||
putResource(t, pool, kind, `{"implement":"openai/gpt"}`, "second")
|
||||
options := StateStoreRecoveryOptions{Operation: RecoveryRollback, Config: configPath, Kind: kind}
|
||||
|
||||
t.Run("refused while the State Store serves", func(t *testing.T) {
|
||||
holdRole(t, url, postgres.OwnerStateStore)
|
||||
if _, err := RunStateStoreRecovery(t.Context(), options); !errors.Is(err, postgres.ErrOwned) {
|
||||
t.Fatalf("rollback with the State Store serving = %v, want ErrOwned", err)
|
||||
}
|
||||
})
|
||||
|
||||
if _, err := RunStateStoreRecovery(t.Context(), options); err != nil {
|
||||
t.Fatalf("rollback: %v", err)
|
||||
}
|
||||
current, err := postgres.NewResources(pool).Resource(t.Context(), storecontract.DefaultOrgID, kind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(current.Value) != `{"implement": "anthropic/claude"}` && string(current.Value) != `{"implement":"anthropic/claude"}` {
|
||||
t.Errorf("value = %s, want the first revision's", current.Value)
|
||||
}
|
||||
if current.Version != 3 {
|
||||
t.Errorf("version = %d, want the rollback recorded as revision 3", current.Version)
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
// startupGrace is how long RunStateStore is given to either refuse the config
|
||||
// or settle into serving before the test cancels it. It bounds "did startup
|
||||
// reject us" (fast, deterministic) rather than "is the machine fast enough"
|
||||
// (I/O-bound, which is what made the previous 200ms budget a coin flip).
|
||||
const startupGrace = 2 * time.Second
|
||||
|
||||
// shutdownGrace bounds how long a cancelled RunStateStore may take to return.
|
||||
const shutdownGrace = 5 * time.Second
|
||||
|
||||
func TestExternalServicesDoNotRequireBridgeNetwork(t *testing.T) {
|
||||
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/_ping"):
|
||||
w.Header().Set("API-Version", "1.55")
|
||||
_, _ = w.Write([]byte("OK"))
|
||||
case strings.HasSuffix(r.URL.Path, "/containers/json"):
|
||||
writeDockerResponse(t, w, []any{})
|
||||
default:
|
||||
http.Error(w, "bridge discovery must not be required", http.StatusBadRequest)
|
||||
}
|
||||
}))
|
||||
defer api.Close()
|
||||
t.Setenv("DOCKER_HOST", api.URL)
|
||||
t.Setenv("DOCKER_API_VERSION", "1.55")
|
||||
t.Setenv("DOCKER_TLS_VERIFY", "")
|
||||
cfg := config.Config{}
|
||||
cfg.NATS.Mode = config.NATSModeExternal
|
||||
cfg.Containers.Network = "host"
|
||||
cfg.Services = config.Services{config.ServiceNameState: {Target: "state.example.test:9090"}}
|
||||
pool, _, cleanup := startContainers(t.Context(), config.NewHolder(cfg), secret.NewRegistry(), slog.New(slog.DiscardHandler))
|
||||
defer cleanup()
|
||||
if pool == nil {
|
||||
t.Fatal("external services on host networking must construct a worker pool")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunStateStoreAcceptsEnvironmentToken(t *testing.T) {
|
||||
t.Setenv("STATE_STORE_TOKEN", "environment-token")
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.toml")
|
||||
data := fmt.Sprintf("bot_user = 'archie'\ndatabase_url = %q\n[forge]\ntype = 'github'\nhost = 'https://github.example.com'\n[[repos]]\nowner = 'acme'\nname = 'widget'\n", pgtest.URL(t))
|
||||
if err := os.WriteFile(path, []byte(data), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Cancellation is the assertion: RunStateStore must start (the env token
|
||||
// satisfies the non-loopback listener) and then return promptly when the
|
||||
// context ends. It must NOT be raced against a wall-clock budget -- SQLite
|
||||
// schema init is I/O, so a test that gives startup a few hundred
|
||||
// milliseconds is a coin flip, not a check. Cancel first, then assert.
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() { errCh <- RunStateStore(ctx, StateStoreOptions{Config: path, Listen: "0.0.0.0:0"}) }()
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
// Returning before cancellation means startup refused the config, which
|
||||
// is the failure this test exists to catch.
|
||||
t.Fatalf("RunStateStore returned before cancellation, want it to serve: %v", err)
|
||||
case <-time.After(startupGrace):
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case err := <-errCh:
|
||||
if err != nil && !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("RunStateStore returned %v, want nil or context.Canceled", err)
|
||||
}
|
||||
case <-time.After(shutdownGrace):
|
||||
t.Fatal("RunStateStore did not return within the shutdown grace after cancellation")
|
||||
}
|
||||
}
|
||||
@@ -1,219 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
|
||||
func TestStateStoreServerOptsLoopbackIsInsecure(t *testing.T) {
|
||||
opts, loopback, err := stateStoreServerOpts("127.0.0.1:9090", "", &staterpc.TaskGrants{})
|
||||
if err != nil {
|
||||
t.Fatalf("stateStoreServerOpts(loopback, no token) error: %v", err)
|
||||
}
|
||||
if !loopback {
|
||||
t.Fatal("loopback listener should report loopback")
|
||||
}
|
||||
if len(opts) != 1 {
|
||||
t.Fatalf("loopback listener should install only the keepalive enforcement policy (no token interceptors), got %d server opts", len(opts))
|
||||
}
|
||||
}
|
||||
|
||||
func TestStateStoreServerOptsNonLoopbackRequiresToken(t *testing.T) {
|
||||
if _, _, err := stateStoreServerOpts("0.0.0.0:9090", "", &staterpc.TaskGrants{}); err == nil {
|
||||
t.Fatal("non-loopback listener without a token should fail closed")
|
||||
}
|
||||
opts, loopback, err := stateStoreServerOpts("0.0.0.0:9090", "secret", &staterpc.TaskGrants{})
|
||||
if err != nil {
|
||||
t.Fatalf("non-loopback listener with a token error: %v", err)
|
||||
}
|
||||
if loopback {
|
||||
t.Fatal("non-loopback listener should not report loopback")
|
||||
}
|
||||
if len(opts) != 3 {
|
||||
t.Fatalf("non-loopback listener should install three server options (the keepalive enforcement policy and the unary and stream task-grant interceptors), got %d", len(opts))
|
||||
}
|
||||
}
|
||||
|
||||
func TestStateStoreServerOptsMalformedListen(t *testing.T) {
|
||||
if _, _, err := stateStoreServerOpts("not-an-address", "", &staterpc.TaskGrants{}); err == nil {
|
||||
t.Fatal("malformed listen address should error")
|
||||
}
|
||||
}
|
||||
|
||||
// TestServeStateStoreServesContract verifies the standalone composition's
|
||||
// serveStateStore + stateStoreDeps wiring actually serves the StateStore gRPC
|
||||
// contract over a real loopback listener: the same service .4.2 serves
|
||||
// in-process, now extracted into its own process. A read-only StatusCounts
|
||||
// call proves the service is registered and wired to the opened store.
|
||||
func TestServeStateStoreServesContract(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
defer st.Close()
|
||||
|
||||
b := newBootstrap()
|
||||
b.st = st
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
defer listener.Close()
|
||||
|
||||
serveCh := make(chan error, 1)
|
||||
go func() { serveCh <- serveStateStore(ctx, listener, b.stateStoreDeps(&staterpc.TaskGrants{}), nil) }()
|
||||
|
||||
conn, err := grpc.NewClient("passthrough:///"+listener.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatalf("dial: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
client := pb.NewStateStoreServiceClient(conn)
|
||||
if _, err := client.StatusCounts(t.Context(), &pb.StatusCountsRequest{}); err != nil {
|
||||
t.Fatalf("StatusCounts over gRPC: %v", err)
|
||||
}
|
||||
|
||||
cancel()
|
||||
select {
|
||||
case err := <-serveCh:
|
||||
if err != nil {
|
||||
t.Fatalf("serveStateStore returned: %v", err)
|
||||
}
|
||||
case <-t.Context().Done():
|
||||
t.Fatal("serveStateStore did not return after cancel")
|
||||
}
|
||||
}
|
||||
|
||||
// TestStateStoreDepsServeTaskLogs proves the standalone State Store process is
|
||||
// where a task-log read is served from: the daemon process holds no dashboard
|
||||
// listener any more, so the service the UI process dials is the only place this
|
||||
// contract can have a server-side reader, and it must be the daemon's own
|
||||
// registry over the state directory.
|
||||
//
|
||||
// Without this wiring the RPC exists and answers Unavailable for every task,
|
||||
// which the dashboard reports as "this process cannot read logs" -- honest, but
|
||||
// still not a working download (archie-core-iaqx).
|
||||
func TestStateStoreDepsServeTaskLogs(t *testing.T) {
|
||||
b := newBootstrap()
|
||||
logs := logging.NewTaskRegistry(filepath.Join(t.TempDir(), "logs", "tasks"), logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
b.taskLogs = logs
|
||||
|
||||
deps := b.stateStoreDeps(&staterpc.TaskGrants{})
|
||||
if deps.TaskLogs == nil {
|
||||
t.Fatal("stateStoreDeps leaves TaskLogs nil; the State Store process is the only server-side reader the dashboard can reach")
|
||||
}
|
||||
if deps.TaskLogs != storecontract.TaskLogStore(logs) {
|
||||
t.Fatalf("TaskLogs = %T, want the daemon's own registry over the state directory", deps.TaskLogs)
|
||||
}
|
||||
// A boot without a registry must not fabricate one: an empty reader would
|
||||
// answer found=false for every attempt, which reads as "the attempt has no
|
||||
// log" rather than "this process cannot read logs".
|
||||
if plain := (&boot{}).stateStoreDeps(&staterpc.TaskGrants{}); plain.TaskLogs != nil {
|
||||
t.Errorf("TaskLogs = %T with no registry on the boot, want nil so the RPC reports unavailability", plain.TaskLogs)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStateStoreDepsServePlaybookDispatcher verifies stateStoreDeps lifts the
|
||||
// opened *pgstore.TaskDB's PlaybookDispatcher surface onto Deps, so the
|
||||
// standalone State Store has a server for the two playbook RPCs. It does not
|
||||
// dial those RPCs here -- it inspects the assembled Deps only. The nil check
|
||||
// is the load-bearing part: a boot without a store must leave
|
||||
// PlaybookDispatcher nil (the server then answers codes.Unavailable) rather
|
||||
// than fabricating a dispatcher.
|
||||
func TestStateStoreDepsServePlaybookDispatcher(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
defer st.Close()
|
||||
|
||||
b := newBootstrap()
|
||||
b.st = st
|
||||
// The playbook ledger, sources and event types are served by the
|
||||
// event-capture store; the task store no longer serves them.
|
||||
eda := pgstore.EDA(t, nil)
|
||||
b.eda = eda
|
||||
deps := b.stateStoreDeps(&staterpc.TaskGrants{})
|
||||
if deps.PlaybookDispatcher == nil {
|
||||
t.Fatal("stateStoreDeps leaves PlaybookDispatcher nil; the standalone State Store is the only production server for the playbook dispatch ledger")
|
||||
}
|
||||
if deps.PlaybookDispatcher != storecontract.PlaybookDispatcher(eda) {
|
||||
t.Fatalf("PlaybookDispatcher = %T, want the opened event-capture store", deps.PlaybookDispatcher)
|
||||
}
|
||||
if deps.Sources == nil || deps.EventTypes == nil {
|
||||
t.Fatalf("stateStoreDeps Sources = %v, EventTypes = %v; want both served, or intake verifies nothing and nothing dispatches", deps.Sources, deps.EventTypes)
|
||||
}
|
||||
// A boot without a store must not fabricate one: nil keeps the RPCs honest
|
||||
// as unavailable rather than depending on a nil receiver.
|
||||
if plain := (&boot{}).stateStoreDeps(&staterpc.TaskGrants{}); plain.PlaybookDispatcher != nil {
|
||||
t.Errorf("PlaybookDispatcher = %T with no store on the boot, want nil so the RPCs report unavailability", plain.PlaybookDispatcher)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStateStoreDataSurvivesRestart is the .4.7 restart/recovery check: a
|
||||
// task written by one archie-state-store process must still be there for a
|
||||
// fresh process opening the same archie.db path, proving b.openStateStore
|
||||
// (RunStateStore's own opener, not a test-only shortcut) round-trips through
|
||||
// the file rather than an in-memory or per-process store.
|
||||
func TestStateStoreDataSurvivesRestart(t *testing.T) {
|
||||
cfg := config.Config{
|
||||
DatabaseURL: pgtest.URL(t),
|
||||
}
|
||||
|
||||
first := newBootstrap()
|
||||
first.cfg = cfg
|
||||
if err := first.openStateStore(t.Context()); err != nil {
|
||||
t.Fatalf("first openStateStore: %v", err)
|
||||
}
|
||||
task, err := first.st.EnqueueChatTask(t.Context(), "acme", "widget", "restart check", "body", "implement", "", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("EnqueueChatTask: %v", err)
|
||||
}
|
||||
first.cleanup() // closes the SQLite handle, simulating process exit
|
||||
|
||||
second := newBootstrap()
|
||||
second.cfg = cfg
|
||||
if err := second.openStateStore(t.Context()); err != nil {
|
||||
t.Fatalf("second openStateStore: %v", err)
|
||||
}
|
||||
defer second.cleanup()
|
||||
|
||||
got, err := second.st.TaskByID(t.Context(), task.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskByID after restart: %v", err)
|
||||
}
|
||||
if got == nil {
|
||||
t.Fatal("task did not survive a restart against the same db path")
|
||||
}
|
||||
if got.Title != task.Title {
|
||||
t.Fatalf("restarted task title = %q, want %q", got.Title, task.Title)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenStoresNeverOwnsTaskDB is the .4.7 single-owner-SQLite assertion:
|
||||
// the daemon/gateway composition path (openStores, run by Run/RunGateway)
|
||||
// must never populate b.st -- that field is reserved for the standalone
|
||||
// archie-state-store binary's openStateStore (state_store.go). Regressing
|
||||
// this would mean archie.db is opened by two processes at once.
|
||||
func TestOpenStoresNeverOwnsTaskDB(t *testing.T) {
|
||||
b := newBootstrap()
|
||||
b.cfg = config.Config{DatabaseURL: pgtest.URL(t)}
|
||||
if err := b.openStores(t.Context()); err != nil {
|
||||
t.Fatalf("openStores: %v", err)
|
||||
}
|
||||
defer b.cleanup()
|
||||
|
||||
if b.st != nil {
|
||||
t.Fatal("openStores populated b.st -- the daemon/gateway path must not own archie.db directly (docs/prds/state-store-contract.md §12 step 7)")
|
||||
}
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
)
|
||||
|
||||
func toolCallEvent(taskID int64, attempt int) events.Event {
|
||||
return events.Event{
|
||||
Kind: events.KindToolCall,
|
||||
TaskID: taskID,
|
||||
Attempt: attempt,
|
||||
Stage: "implement",
|
||||
Detail: "all checks passed",
|
||||
Data: map[string]any{"tool": "shell", "failed": false},
|
||||
At: time.Now().UTC(),
|
||||
Workflow: "tdd",
|
||||
}
|
||||
}
|
||||
|
||||
// TestInsertEventProjectsToolCall pins the projection (test a): one tool_call
|
||||
// event through the decorated store persists the event AND exactly one
|
||||
// tool_calls row, with the row's fields taken from the event -- the tool name
|
||||
// from data, the output summary in result for a succeeded call.
|
||||
func TestInsertEventProjectsToolCall(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
ts := newToolCallProjectingTaskStore(st, eda, slog.Default())
|
||||
|
||||
id, err := ts.InsertEvent(t.Context(), toolCallEvent(42, 2))
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEvent() error = %v", err)
|
||||
}
|
||||
if id == 0 {
|
||||
t.Fatal("InsertEvent() returned id 0; the event itself must still persist")
|
||||
}
|
||||
|
||||
rows, err := eda.TaskToolCalls(t.Context(), 42)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskToolCalls() error = %v", err)
|
||||
}
|
||||
if len(rows) != 1 {
|
||||
t.Fatalf("TaskToolCalls() returned %d rows, want exactly one per tool_call event: %+v", len(rows), rows)
|
||||
}
|
||||
row := rows[0]
|
||||
if row.TaskID != 42 || row.Attempt != 2 {
|
||||
t.Errorf("row task/attempt = %d/%d, want 42/2", row.TaskID, row.Attempt)
|
||||
}
|
||||
if row.Tool != "shell" {
|
||||
t.Errorf("row tool = %q, want \"shell\" from the event's data", row.Tool)
|
||||
}
|
||||
if row.Result != "all checks passed" {
|
||||
t.Errorf("row result = %q, want the event detail of a succeeded call", row.Result)
|
||||
}
|
||||
if row.Error != "" {
|
||||
t.Errorf("row error = %q, want empty for a succeeded call", row.Error)
|
||||
}
|
||||
if row.CalledAt.IsZero() {
|
||||
t.Error("row called_at is zero; it must carry the event time")
|
||||
}
|
||||
}
|
||||
|
||||
// TestInsertEventProjectsFailedToolCall pins the failure column: a tool_call
|
||||
// event whose call failed stores its detail under error, not result, so the
|
||||
// transcript can distinguish the two without re-parsing text.
|
||||
func TestInsertEventProjectsFailedToolCall(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
ts := newToolCallProjectingTaskStore(st, eda, slog.Default())
|
||||
|
||||
e := toolCallEvent(42, 2)
|
||||
e.Detail = "error: no such file"
|
||||
e.Data = map[string]any{"tool": "read_file", "failed": true}
|
||||
if _, err := ts.InsertEvent(t.Context(), e); err != nil {
|
||||
t.Fatalf("InsertEvent() error = %v", err)
|
||||
}
|
||||
|
||||
rows, err := eda.TaskToolCalls(t.Context(), 42)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskToolCalls() error = %v", err)
|
||||
}
|
||||
if len(rows) != 1 {
|
||||
t.Fatalf("TaskToolCalls() returned %d rows, want 1", len(rows))
|
||||
}
|
||||
if rows[0].Error != "error: no such file" {
|
||||
t.Errorf("row error = %q, want the failed call's detail", rows[0].Error)
|
||||
}
|
||||
if rows[0].Result != "" {
|
||||
t.Errorf("row result = %q, want empty for a failed call", rows[0].Result)
|
||||
}
|
||||
}
|
||||
|
||||
// TestInsertEventLeavesOtherKindsUnprojected pins the kind gate: only
|
||||
// tool_call events reach the collection; the task timeline's other kinds must
|
||||
// not grow tool_calls rows.
|
||||
func TestInsertEventLeavesOtherKindsUnprojected(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
ts := newToolCallProjectingTaskStore(st, eda, slog.Default())
|
||||
|
||||
if _, err := ts.InsertEvent(t.Context(), events.Event{
|
||||
Kind: events.KindStageFinish, TaskID: 42, Attempt: 2,
|
||||
Data: map[string]any{"duration_ms": 12.0},
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertEvent() error = %v", err)
|
||||
}
|
||||
|
||||
rows, err := eda.TaskToolCalls(t.Context(), 42)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskToolCalls() error = %v", err)
|
||||
}
|
||||
if len(rows) != 0 {
|
||||
t.Fatalf("TaskToolCalls() returned %d rows for a stage_finish event, want 0", len(rows))
|
||||
}
|
||||
}
|
||||
|
||||
// failingToolCallWriter stands in for a broken event-capture store, so the
|
||||
// never-returned-failure contract can be tested without sabotaging the real
|
||||
// store.
|
||||
type failingToolCallWriter struct{ err error }
|
||||
|
||||
func (f failingToolCallWriter) InsertToolCall(context.Context, postgres.ToolCall) error {
|
||||
return f.err
|
||||
}
|
||||
|
||||
// TestInsertEventSucceedsWhenProjectionFails pins the load-bearing half of the
|
||||
// contract: a tool_calls write failure is never returned from InsertEvent --
|
||||
// event persistence is the contract, the projection is observability -- and
|
||||
// the failure is recorded, not swallowed silently.
|
||||
func TestInsertEventSucceedsWhenProjectionFails(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
var buf bytes.Buffer
|
||||
ts := newToolCallProjectingTaskStore(st, failingToolCallWriter{
|
||||
err: errors.New("disk on fire"),
|
||||
}, slog.New(slog.NewTextHandler(&buf, nil)))
|
||||
|
||||
id, err := ts.InsertEvent(t.Context(), toolCallEvent(42, 2))
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEvent() error = %v; a projection failure must never fail the event write", err)
|
||||
}
|
||||
if id == 0 {
|
||||
t.Fatal("InsertEvent() returned id 0; the event must still persist")
|
||||
}
|
||||
if got := ts.toolCallProjectionFailures(); got != 1 {
|
||||
t.Errorf("toolCallProjectionFailures() = %d, want 1: the failure must be counted, not swallowed", got)
|
||||
}
|
||||
if !strings.Contains(buf.String(), "disk on fire") {
|
||||
t.Errorf("log output %q does not carry the projection failure; it was swallowed silently", buf.String())
|
||||
}
|
||||
// The event row is what the whole surface exists for -- it must be there.
|
||||
persisted, err := st.TaskEvents(t.Context(), 42)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskEvents() error = %v", err)
|
||||
}
|
||||
if len(persisted) != 1 {
|
||||
t.Fatalf("TaskEvents() returned %d events, want 1: the event persisted despite the projection failure", len(persisted))
|
||||
}
|
||||
}
|
||||
|
||||
// TestStateStoreDepsProjectToolCalls pins the wire-in: with both stores open,
|
||||
// the composition serves Tasks as the projecting decorator; with no
|
||||
// event-capture store, Tasks is passed through untouched rather than wrapped
|
||||
// around a nil writer.
|
||||
func TestStateStoreDepsProjectToolCalls(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
|
||||
b := newBootstrap()
|
||||
b.st = st
|
||||
b.eda = pgstore.EDA(t, nil)
|
||||
deps := b.stateStoreDeps(&staterpc.TaskGrants{})
|
||||
if _, ok := deps.Tasks.(*toolCallProjectingTaskStore); !ok {
|
||||
t.Fatalf("deps.Tasks = %T, want the tool_call projecting decorator", deps.Tasks)
|
||||
}
|
||||
|
||||
plain := newBootstrap()
|
||||
plain.st = st
|
||||
plainDeps := plain.stateStoreDeps(&staterpc.TaskGrants{})
|
||||
if _, ok := plainDeps.Tasks.(*toolCallProjectingTaskStore); ok {
|
||||
t.Fatal("deps.Tasks is decorated with no event-capture store on the boot; the projection would write through a nil writer")
|
||||
}
|
||||
}
|
||||
@@ -1,482 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
"github.com/samcharles93/ai-sdk/chat"
|
||||
"github.com/samcharles93/ai-sdk/core"
|
||||
"github.com/samcharles93/ai-sdk/runtime"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/container"
|
||||
"github.com/samcharles93/archie-core/internal/daemon"
|
||||
"github.com/samcharles93/archie-core/internal/domain/curator"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// TestProviderOutcomeRecorderRecordsTheLastCallOnly pins the producer behind
|
||||
// /status' chat-model line: it reports what actually happened, and the moment
|
||||
// something else happens it reports that instead. There is no probe anywhere
|
||||
// in this path -- a chat command must not pay a network round trip, and a
|
||||
// probe would answer for the probe's connection, not the daemon's.
|
||||
func TestProviderOutcomeRecorderRecordsTheLastCallOnly(t *testing.T) {
|
||||
failure := errors.New("401 Unauthorized")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
record func(*providerOutcomeRecorder)
|
||||
wantAttempted bool
|
||||
wantErr string
|
||||
wantModel string
|
||||
}{
|
||||
{
|
||||
name: "nothing recorded yet",
|
||||
record: func(*providerOutcomeRecorder) {},
|
||||
wantAttempted: false,
|
||||
},
|
||||
{
|
||||
name: "successful call",
|
||||
record: func(r *providerOutcomeRecorder) { r.record("openai/gpt-5.6", nil) },
|
||||
wantAttempted: true,
|
||||
wantModel: "openai/gpt-5.6",
|
||||
},
|
||||
{
|
||||
name: "failed call",
|
||||
record: func(r *providerOutcomeRecorder) { r.record("openai/gpt-5.6", failure) },
|
||||
wantAttempted: true,
|
||||
wantErr: "401 Unauthorized",
|
||||
wantModel: "openai/gpt-5.6",
|
||||
},
|
||||
{
|
||||
name: "a later success replaces an earlier failure",
|
||||
record: func(r *providerOutcomeRecorder) {
|
||||
r.record("openai/gpt-5.6", failure)
|
||||
r.record("deepseek/deepseek-v4-pro", nil)
|
||||
},
|
||||
wantAttempted: true,
|
||||
wantModel: "deepseek/deepseek-v4-pro",
|
||||
},
|
||||
{
|
||||
name: "a later failure replaces an earlier success",
|
||||
record: func(r *providerOutcomeRecorder) {
|
||||
r.record("openai/gpt-5.6", nil)
|
||||
r.record("openai/gpt-5.6", failure)
|
||||
},
|
||||
wantAttempted: true,
|
||||
wantErr: "401 Unauthorized",
|
||||
wantModel: "openai/gpt-5.6",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
recorder := newProviderOutcomeRecorder()
|
||||
before := time.Now().Add(-time.Second)
|
||||
tc.record(recorder)
|
||||
|
||||
outcome, attempted := recorder.LastChatModelOutcome()
|
||||
if attempted != tc.wantAttempted {
|
||||
t.Fatalf("LastChatModelOutcome() attempted = %v, want %v", attempted, tc.wantAttempted)
|
||||
}
|
||||
if !tc.wantAttempted {
|
||||
return
|
||||
}
|
||||
if outcome.Err != tc.wantErr {
|
||||
t.Errorf("outcome.Err = %q, want %q", outcome.Err, tc.wantErr)
|
||||
}
|
||||
if outcome.Model != tc.wantModel {
|
||||
t.Errorf("outcome.Model = %q, want %q", outcome.Model, tc.wantModel)
|
||||
}
|
||||
if outcome.At.Before(before) || outcome.At.After(time.Now()) {
|
||||
t.Errorf("outcome.At = %v, want a time within the call's window", outcome.At)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// sendChatTurn is written to tolerate a nil recorder (a call path built
|
||||
// without one must not panic), and a nil recorder must claim nothing.
|
||||
var absent *providerOutcomeRecorder
|
||||
absent.record("openai/gpt-5.6", failure)
|
||||
if _, attempted := absent.LastChatModelOutcome(); attempted {
|
||||
t.Error("a nil recorder reported an attempted call; it has nothing to report")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSendChatTurnRecordsEachCallOutcome pins the wire between the chat path
|
||||
// and /status: sendChatTurn is the single point every chat-model call in this
|
||||
// process passes through, and it must record what happened there rather than
|
||||
// trusting each caller to remember. A recorder that is never written is the
|
||||
// failure this pins -- /status would say "no calls attempted yet" forever
|
||||
// while chat worked, which reads as a broken provider rather than a broken
|
||||
// wire.
|
||||
func TestSendChatTurnRecordsEachCallOutcome(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
reply string
|
||||
status int
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "successful call",
|
||||
reply: `{"id":"chatcmpl-1","object":"chat.completion","created":1,"model":"gpt-5.6","choices":[{"index":0,"message":{"role":"assistant","content":"hello"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`,
|
||||
status: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "failed call",
|
||||
reply: `{"error":{"message":"invalid api key","type":"invalid_request_error"}}`,
|
||||
status: http.StatusUnauthorized,
|
||||
wantErr: "invalid api key",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var requestedPath string
|
||||
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestedPath = r.URL.Path
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(tc.status)
|
||||
_, _ = io.WriteString(w, tc.reply)
|
||||
}))
|
||||
t.Cleanup(api.Close)
|
||||
|
||||
llm := agentexec.NewRuntime(map[string]agentexec.Provider{
|
||||
"openai": {Class: "openai", BaseURL: api.URL},
|
||||
})
|
||||
if llm == nil {
|
||||
t.Fatal("NewRuntime = nil, want a runtime for the configured provider")
|
||||
}
|
||||
|
||||
recorder := newProviderOutcomeRecorder()
|
||||
_, err := sendChatTurn(t.Context(), llm, "openai/gpt-5.6", core.GenerateOptions{
|
||||
Messages: []chat.Message{{Role: chat.RoleUser, Content: "hi"}},
|
||||
MaxSteps: 1,
|
||||
}, nil, recorder, nil)
|
||||
|
||||
if tc.wantErr == "" && err != nil {
|
||||
t.Fatalf("sendChatTurn = %v, want success (request path %q)", err, requestedPath)
|
||||
}
|
||||
if tc.wantErr != "" && (err == nil || !strings.Contains(err.Error(), tc.wantErr)) {
|
||||
t.Fatalf("sendChatTurn = %v, want an error containing %q", err, tc.wantErr)
|
||||
}
|
||||
|
||||
outcome, attempted := recorder.LastChatModelOutcome()
|
||||
if !attempted {
|
||||
t.Fatal("recorded outcome = attempted false, want the call recorded at sendChatTurn")
|
||||
}
|
||||
if outcome.Model != "openai/gpt-5.6" {
|
||||
t.Errorf("outcome.Model = %q, want the model the call used", outcome.Model)
|
||||
}
|
||||
if got := outcome.Err != ""; got != (tc.wantErr != "") {
|
||||
t.Errorf("outcome.Err = %q, want an error report = %v", outcome.Err, tc.wantErr != "")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestStatusHealthOmitsSourcesThisProcessDoesNotOwn pins "truthful or
|
||||
// absent": with no subsystem wired, the report is empty rather than full of
|
||||
// zeroes that read as measurements. This is the shape the standalone Gateway
|
||||
// process produces -- it owns no container pool, no poll loop and no channel
|
||||
// manager, and must not pretend otherwise.
|
||||
func TestStatusHealthOmitsSourcesThisProcessDoesNotOwn(t *testing.T) {
|
||||
report := statusHealth{}.Health()
|
||||
|
||||
if report.Broker != nil {
|
||||
t.Errorf("Broker = %+v, want nil when this process holds no broker connection", report.Broker)
|
||||
}
|
||||
if report.Containers != nil {
|
||||
t.Errorf("Containers = %+v, want nil when this process owns no container pool", report.Containers)
|
||||
}
|
||||
if report.ChatModel != nil {
|
||||
t.Errorf("ChatModel = %+v, want nil when this process records no model calls", report.ChatModel)
|
||||
}
|
||||
if report.Channels != nil {
|
||||
t.Errorf("Channels = %+v, want nil when this process owns no channel manager", report.Channels)
|
||||
}
|
||||
if report.LastPoll != nil {
|
||||
t.Errorf("LastPoll = %+v, want nil when this process does not poll", report.LastPoll)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStatusHealthReportsOnlyBrokerAndChatModel pins what every /status
|
||||
// surface actually serves. The only production router.Health is the Gateway's,
|
||||
// and the facts the Gateway holds are the ones this boot is given here. A
|
||||
// producer wired to the pool or the poll loop would build a section nothing in
|
||||
// this process can serve -- the operator would read a full health list in a
|
||||
// process that has no container pool, and would read it as measured.
|
||||
func TestStatusHealthReportsOnlyBrokerAndChatModel(t *testing.T) {
|
||||
srv := startEmbeddedNATS(t)
|
||||
conn, err := natsio.Connect(srv.ClientURL())
|
||||
if err != nil {
|
||||
t.Fatalf("nats connect: %v", err)
|
||||
}
|
||||
t.Cleanup(conn.Close)
|
||||
|
||||
recorder := newProviderOutcomeRecorder()
|
||||
recorder.record("openai/gpt-5.6", nil)
|
||||
|
||||
// The pool and the daemon are present here on purpose: the daemon
|
||||
// composition holds both, so a producer reading them would claim a
|
||||
// container and poll line from a process whose router cannot serve it.
|
||||
b := &boot{
|
||||
taskActionsConn: conn,
|
||||
providerOutcomes: recorder,
|
||||
containerPool: &container.Pool{},
|
||||
d: &daemon.Daemon{},
|
||||
}
|
||||
|
||||
report := newStatusHealth(b).Health()
|
||||
|
||||
if report.Broker == nil || !report.Broker.Connected {
|
||||
t.Errorf("Broker = %+v, want this process's own connected broker connection", report.Broker)
|
||||
}
|
||||
if report.ChatModel == nil || !report.ChatModel.Attempted {
|
||||
t.Errorf("ChatModel = %+v, want the recorded call", report.ChatModel)
|
||||
}
|
||||
if report.Containers != nil {
|
||||
t.Errorf("Containers = %+v, want nil: no /status surface is served from this boot's pool", report.Containers)
|
||||
}
|
||||
if report.Channels != nil {
|
||||
t.Errorf("Channels = %+v, want nil: no /status surface is served from this boot's channels", report.Channels)
|
||||
}
|
||||
if report.LastPoll != nil {
|
||||
t.Errorf("LastPoll = %v, want nil: no /status surface is served from this boot's poll loop", report.LastPoll)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStatusHealthReportsEveryWiredSource pins that each wired source reaches
|
||||
// the report, and that a source reporting "nothing has happened yet" stays
|
||||
// distinguishable from an absent source.
|
||||
func TestStatusHealthReportsEveryWiredSource(t *testing.T) {
|
||||
recorder := newProviderOutcomeRecorder()
|
||||
recorder.record("openai/gpt-5.6", errors.New("401 Unauthorized"))
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
check func(*testing.T, gateway.HealthReport)
|
||||
src statusHealth
|
||||
}{
|
||||
{
|
||||
name: "broker",
|
||||
src: statusHealth{broker: func() (bool, bool) { return true, true }},
|
||||
check: func(t *testing.T, r gateway.HealthReport) {
|
||||
if r.Broker == nil || !r.Broker.Connected {
|
||||
t.Errorf("Broker = %+v, want connected", r.Broker)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "chat model recorder",
|
||||
src: statusHealth{chatModel: recorder},
|
||||
check: func(t *testing.T, r gateway.HealthReport) {
|
||||
if r.ChatModel == nil || !r.ChatModel.Attempted {
|
||||
t.Fatalf("ChatModel = %+v, want the recorded call", r.ChatModel)
|
||||
}
|
||||
if r.ChatModel.Outcome.Err != "401 Unauthorized" {
|
||||
t.Errorf("ChatModel.Outcome.Err = %q, want the recorded error", r.ChatModel.Outcome.Err)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "chat model recorder with no calls yet",
|
||||
src: statusHealth{chatModel: newProviderOutcomeRecorder()},
|
||||
check: func(t *testing.T, r gateway.HealthReport) {
|
||||
if r.ChatModel == nil {
|
||||
t.Fatal("ChatModel = nil, want a present section saying nothing has been attempted")
|
||||
}
|
||||
if r.ChatModel.Attempted {
|
||||
t.Error("ChatModel.Attempted = true, want false before any call")
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
tc.check(t, tc.src.Health())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetupGatewayChatCarriesStatusHealth pins the last hop: the router the
|
||||
// composition root builds must expose the health source, or /status answers
|
||||
// from the queue and runtime sections alone while the composition root
|
||||
// believes health is wired.
|
||||
//
|
||||
// Asserted on the source rather than by calling setupGatewayChat, which needs
|
||||
// a fully built boot (stores, runtime, memory engines) to run. That is the
|
||||
// same technique composition_order_test.go uses for wiring nothing at runtime
|
||||
// observes. The predecessor of this test drove buildTelegramRouter, which the
|
||||
// Messaging Service extraction deleted along with the daemon's own routers;
|
||||
// setupGatewayChat is now the sole production constructor of a Router.
|
||||
func TestSetupGatewayChatCarriesStatusHealth(t *testing.T) {
|
||||
fileset := token.NewFileSet()
|
||||
file, err := parser.ParseFile(fileset, "gateway_runtime.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := methodBody(t, file, "setupGatewayChat")
|
||||
|
||||
var wired bool
|
||||
ast.Inspect(body, func(n ast.Node) bool {
|
||||
assign, ok := n.(*ast.AssignStmt)
|
||||
if !ok || len(assign.Lhs) != 1 {
|
||||
return true
|
||||
}
|
||||
sel, ok := assign.Lhs[0].(*ast.SelectorExpr)
|
||||
if !ok || sel.Sel.Name != "Health" {
|
||||
return true
|
||||
}
|
||||
if ident, ok := sel.X.(*ast.Ident); ok && ident.Name == "router" {
|
||||
wired = true
|
||||
}
|
||||
return true
|
||||
})
|
||||
if !wired {
|
||||
t.Fatal("setupGatewayChat never assigns router.Health; /status would lose its health section")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRouterWithHealthAnswersStatus is the behavioural half: a router holding a
|
||||
// health source renders it into /status.
|
||||
func TestRouterWithHealthAnswersStatus(t *testing.T) {
|
||||
sessions := gateway.NewSessionStoreMemory()
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
|
||||
st := pgstore.Open(t)
|
||||
router := gateway.NewRouter(st, nil, "web")
|
||||
router.InitSessions(sessions)
|
||||
router.Health = statusHealth{broker: func() (bool, bool) { return true, true }}
|
||||
|
||||
reply, err := router.Route(context.Background(), gateway.Inbound{
|
||||
Message: messaging.Message{Role: messaging.RoleUser, Text: "/status"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Route(/status): %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "Broker: connected") {
|
||||
t.Errorf("reply = %q, want the wired broker line", reply)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordKeepsTheLatestOutcomeUnderReordering is the regression case for a
|
||||
// /status chat-model line that reports an older call as the latest. The
|
||||
// completion time is taken before the lock, so two concurrent calls can reach
|
||||
// the lock in the opposite order to their completion; an unconditional store
|
||||
// then overwrites the newer outcome with the older one.
|
||||
func TestRecordKeepsTheLatestOutcomeUnderReordering(t *testing.T) {
|
||||
r := &providerOutcomeRecorder{}
|
||||
newer := time.Now().UTC()
|
||||
older := newer.Add(-time.Minute)
|
||||
|
||||
// The later call completes and stores first, as it would when the earlier
|
||||
// call is descheduled between stamping and locking.
|
||||
r.recordAt("openai/gpt-5.6", nil, newer)
|
||||
r.recordAt("openai/gpt-4o", errors.New("401 Unauthorized"), older)
|
||||
|
||||
got, attempted := r.LastChatModelOutcome()
|
||||
if !attempted {
|
||||
t.Fatal("LastChatModelOutcome reports no attempt after two records")
|
||||
}
|
||||
if got.Model != "openai/gpt-5.6" || got.Err != "" {
|
||||
t.Fatalf("outcome = %+v, want the newer successful call to survive", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordStoresTheFirstOutcomeWhateverItsAge pins that the ordering guard
|
||||
// does not swallow the first record, whose timestamp has nothing to compare
|
||||
// against.
|
||||
func TestRecordStoresTheFirstOutcomeWhateverItsAge(t *testing.T) {
|
||||
r := &providerOutcomeRecorder{}
|
||||
r.recordAt("openai/gpt-4o", nil, time.Now().UTC().Add(-time.Hour))
|
||||
|
||||
if _, attempted := r.LastChatModelOutcome(); !attempted {
|
||||
t.Fatal("the first recorded outcome was dropped")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCuratorRunnerRefusesWithoutARuntime pins that a curator asking for a
|
||||
// completion on a daemon with no configured provider gets an error. The
|
||||
// runtime constructor returns nil in that case, and a nil *runtime.Runtime
|
||||
// panics on its first method call, which would take the daemon down. Nothing
|
||||
// is recorded: no provider call was attempted, and saying one failed would be
|
||||
// a /status that blames the provider for a local misconfiguration.
|
||||
func TestCuratorRunnerRefusesWithoutARuntime(t *testing.T) {
|
||||
recorder := &providerOutcomeRecorder{}
|
||||
runner := curatorLLMRunner{outcomes: recorder}
|
||||
|
||||
if _, err := runner.Chat(context.Background(), curator.ChatRequest{Model: "openai/gpt-4o"}); err == nil {
|
||||
t.Fatal("Chat with no runtime returned no error")
|
||||
}
|
||||
if _, attempted := recorder.LastChatModelOutcome(); attempted {
|
||||
t.Error("a local misconfiguration was recorded as a provider call")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCuratorRunnerRecordsItsOutcome pins that curator model calls reach
|
||||
// /status. They do not pass through sendChatTurn, so before this a daemon
|
||||
// whose only recent model traffic was curator work reported "no calls
|
||||
// attempted yet" while the provider was demonstrably reachable.
|
||||
func TestCuratorRunnerRecordsItsOutcome(t *testing.T) {
|
||||
recorder := &providerOutcomeRecorder{}
|
||||
// A provider pointed at a closed local port fails fast without touching
|
||||
// the network. The outcome is what matters here: a failed provider call is
|
||||
// exactly what /status must not miss.
|
||||
rt := agentexec.NewRuntime(map[string]agentexec.Provider{
|
||||
"openai": {Class: "openai", BaseURL: "http://127.0.0.1:1", APIKeyEnv: "ARCHIE_TEST_MISSING_KEY"},
|
||||
})
|
||||
if rt == nil {
|
||||
t.Fatal("NewRuntime returned nil for a configured provider")
|
||||
}
|
||||
runner := curatorLLMRunner{llm: func() *runtime.Runtime { return rt }, outcomes: recorder}
|
||||
|
||||
_, err := runner.Chat(context.Background(), curator.ChatRequest{Model: "openai/gpt-4o"})
|
||||
if err == nil {
|
||||
t.Fatal("Chat against a closed port returned no error")
|
||||
}
|
||||
|
||||
got, attempted := recorder.LastChatModelOutcome()
|
||||
if !attempted {
|
||||
t.Fatal("curator call was not recorded; /status would report no calls attempted")
|
||||
}
|
||||
if got.Model != "openai/gpt-4o" || got.Err == "" {
|
||||
t.Fatalf("outcome = %+v, want the failed curator call", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTitleGenerationDoesNotRecordChatModelHealth is the regression case for
|
||||
// /status blaming the provider for a cosmetic failure. Title generation runs
|
||||
// detached after a first turn under its own 30s bound and its error is
|
||||
// swallowed by the caller, so a title that merely timed out must not become
|
||||
// the process-wide "Chat model: failed" that an operator reads as an outage.
|
||||
func TestTitleGenerationDoesNotRecordChatModelHealth(t *testing.T) {
|
||||
recorder := &providerOutcomeRecorder{}
|
||||
rt := agentexec.NewRuntime(map[string]agentexec.Provider{
|
||||
"openai": {Class: "openai", BaseURL: "http://127.0.0.1:1", APIKeyEnv: "ARCHIE_TEST_MISSING_KEY"},
|
||||
})
|
||||
if rt == nil {
|
||||
t.Fatal("NewRuntime returned nil for a configured provider")
|
||||
}
|
||||
gen := &chatTitleGenerator{llm: func() *runtime.Runtime { return rt }, chatModels: newChatModelManager(map[string]string{"chat": "openai/gpt-4o"}, nil, nil)}
|
||||
|
||||
if _, err := gen.GenerateTitle(context.Background(), "s1", "hello"); err == nil {
|
||||
t.Fatal("GenerateTitle against a closed port returned no error")
|
||||
}
|
||||
if _, attempted := recorder.LastChatModelOutcome(); attempted {
|
||||
t.Error("a failed title proposal was recorded as chat-model health")
|
||||
}
|
||||
}
|
||||
@@ -1,272 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
|
||||
)
|
||||
|
||||
// stepVocabularyProbe is a provider set of one, used only to prove the manager
|
||||
// a root builds is live: registering through it must reach its vocabulary.
|
||||
type stepVocabularyProbe struct{}
|
||||
|
||||
func (stepVocabularyProbe) Name() string { return "probe" }
|
||||
|
||||
func (stepVocabularyProbe) StepTypes() []workflow.StepType {
|
||||
return []workflow.StepType{{Name: "probe.registered", Factory: func(yaml.Node) (workflow.Stage, error) {
|
||||
return workflow.Stage{Name: "probe.registered"}, nil
|
||||
}}}
|
||||
}
|
||||
|
||||
// sharedStepTypeNames returns the step types the shared provider set
|
||||
// (internal/infrastructure/workflowsteps) declares. It is read through the same
|
||||
// Providers() seam the composition roots register, rather than from
|
||||
// workflow.BuiltinStepRegistry(): the shipped stages arrive by registration, and
|
||||
// a provider added to that set is the documented way a step type enters every
|
||||
// binary at once.
|
||||
func sharedStepTypeNames() []string {
|
||||
names := make([]string, 0)
|
||||
for _, provider := range workflowsteps.Providers() {
|
||||
for _, stepType := range provider.StepTypes() {
|
||||
names = append(names, stepType.Name)
|
||||
}
|
||||
}
|
||||
slices.Sort(names)
|
||||
return names
|
||||
}
|
||||
|
||||
// requireSharedStepVocabulary holds a composition root's manager to both halves
|
||||
// of the contract: it resolves the shipped vocabulary, and it is live enough to
|
||||
// take a provider registered through it.
|
||||
func requireSharedStepVocabulary(t *testing.T, steps *workflow.Manager) {
|
||||
t.Helper()
|
||||
if steps == nil {
|
||||
t.Fatal("the composition root registered no workflow step vocabulary")
|
||||
}
|
||||
got := steps.StepTypes()
|
||||
// Containment, not equality: adding a provider to the shared set is the
|
||||
// documented way a step type arrives, and that must not have to edit this
|
||||
// guard. What the guard holds is that no shipped stage is missing, which is
|
||||
// what a root regressing to workflow.NewManager() loses.
|
||||
for name := range workflow.BuiltinStepRegistry() {
|
||||
if !slices.Contains(got, name) {
|
||||
t.Errorf("the composition root resolves %v, which is missing the shipped stage %q", got, name)
|
||||
}
|
||||
}
|
||||
// The other half is provenance: every name the root resolves must be
|
||||
// declared by the shared provider set, not by a near-identical provider of
|
||||
// the root's own. That set is what ties this process's vocabulary to the
|
||||
// other side of the contract. It is content, not identity -- the shipped
|
||||
// provider rebuilds its factories on every call -- so a root that stopped
|
||||
// importing the shared set and hand-rolled an equal one would still pass.
|
||||
declared := sharedStepTypeNames()
|
||||
for _, name := range got {
|
||||
if !slices.Contains(declared, name) {
|
||||
t.Errorf("the composition root resolves %q, which no provider in the shared set declares", name)
|
||||
}
|
||||
}
|
||||
if err := steps.Register(stepVocabularyProbe{}); err != nil {
|
||||
t.Fatalf("register a provider through the root's manager: %v", err)
|
||||
}
|
||||
if _, resolved := steps.Registry()["probe.registered"]; !resolved {
|
||||
t.Fatal("a provider registered through the root's manager did not reach its vocabulary")
|
||||
}
|
||||
}
|
||||
|
||||
// TestStepVocabularyRegistersTheSharedProviderSet pins the unit the daemon root
|
||||
// resolves its vocabulary from. Handing this function an empty manager
|
||||
// (workflow.NewManager) would leave the daemon unable to decode the stored
|
||||
// definitions it pins onto tasks.
|
||||
func TestStepVocabularyRegistersTheSharedProviderSet(t *testing.T) {
|
||||
steps, err := stepVocabulary()
|
||||
if err != nil {
|
||||
t.Fatalf("stepVocabulary: %v", err)
|
||||
}
|
||||
requireSharedStepVocabulary(t, steps)
|
||||
}
|
||||
|
||||
// TestArchiedRootsResolveTheStepVocabularyFromThatFunction pins both halves of
|
||||
// each root's wiring: the root reaches the vocabulary through stepVocabulary,
|
||||
// and the manager it returns is the one handed to the constructor that resolves
|
||||
// a step type with it. Neither root can be executed in a unit test -- Run owns
|
||||
// a SQLite file and a listen address, openDaemonWorkflowDefinitions dials the
|
||||
// State Store -- so both are asserted by source position, the way
|
||||
// composition_order_test.go pins the memory-engine ordering for the same
|
||||
// reason. A root that built its own manager, or built one and handed the
|
||||
// constructor a different one, would resolve a vocabulary without the shipped
|
||||
// stages.
|
||||
func TestArchiedRootsResolveTheStepVocabularyFromThatFunction(t *testing.T) {
|
||||
for _, link := range []struct{ file, function, constructor string }{
|
||||
// The validating side: the State Store's control plane server.
|
||||
{"state_store.go", "openStateStoreControlPlane", "NewServer"},
|
||||
// The executing side's client, built by the daemon root alone.
|
||||
{"step_vocabulary.go", "openDaemonWorkflowDefinitions", "NewWorkflowDefinitionsClient"},
|
||||
} {
|
||||
t.Run(link.function+"->stepVocabulary->"+link.constructor, func(t *testing.T) {
|
||||
body := parsedBody(t, link.file, link.function)
|
||||
manager := stepVocabularyAssignment(body)
|
||||
if manager == "" {
|
||||
t.Fatalf("%s does not build its step vocabulary through stepVocabulary()", link.function)
|
||||
}
|
||||
if !callPassesIdent(body, link.constructor, manager) {
|
||||
t.Errorf("%s does not hand the manager stepVocabulary() returned (%s) to %s()", link.function, manager, link.constructor)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnlyTheDaemonRootRegistersAStepVocabulary pins the cut the shape applies
|
||||
// to every other process: a root that cannot resolve a step type registers no
|
||||
// vocabulary and cannot be failed by one. openStateStoreAdapter is shared by the
|
||||
// daemon and the gateway, and the gateway resolves no step type -- its
|
||||
// control-plane surfaces are catalog, runtime settings and personas -- so the
|
||||
// vocabulary belongs to the daemon root alone, exactly as
|
||||
// internal/app/archiemessaging's dead vocabulary was removed. Asserted by
|
||||
// source position for the same reason as above.
|
||||
func TestOnlyTheDaemonRootRegistersAStepVocabulary(t *testing.T) {
|
||||
if pos := identCallPosition(parsedBody(t, "bootstrap.go", "openStateStoreAdapter"), "stepVocabulary"); pos != token.NoPos {
|
||||
t.Error("openStateStoreAdapter registers a step vocabulary; it is shared with the gateway root, which never resolves a step type")
|
||||
}
|
||||
if fileMentionsIdent(t, "gateway.go", "stepVocabulary") {
|
||||
t.Error("the gateway root file mentions stepVocabulary; the gateway resolves no workflow step type")
|
||||
}
|
||||
|
||||
// The daemon root opens the state stage -- the shared adapter, the
|
||||
// daemon-only definitions client and the access chain -- through one
|
||||
// call, so the sequence costs Run a single branch. The guarantee is the
|
||||
// one this pin always held, relocated to where the sequence now lives:
|
||||
// adapter first, then the client built on its transport, both before
|
||||
// buildDaemon captures the client.
|
||||
run := parsedBody(t, "main.go", "Run")
|
||||
stage := methodCallPosition(run, "openStateStage")
|
||||
build := methodCallPosition(run, "buildDaemon")
|
||||
if stage == token.NoPos {
|
||||
t.Fatal("Run never opens the daemon's state stage; every task pin would fall back to the shipped definitions")
|
||||
}
|
||||
if build == token.NoPos || stage > build {
|
||||
t.Errorf("Run opens the state stage at %v, after buildDaemon at %v: the daemon would capture no definitions surface", stage, build)
|
||||
}
|
||||
// No half of the stage may also be opened from Run directly: a second
|
||||
// call site would be a copy of the sequence outside the order asserted
|
||||
// below.
|
||||
for _, direct := range []string{"openStateStoreAdapter", "openDaemonWorkflowDefinitions", "openDaemonStateSurfaces", "openAccessChain"} {
|
||||
if pos := methodCallPosition(run, direct); pos != token.NoPos {
|
||||
t.Errorf("Run calls %s directly at %v; the state stage opens through openStateStage alone", direct, pos)
|
||||
}
|
||||
}
|
||||
|
||||
sequence := parsedBody(t, "step_vocabulary.go", "openDaemonStateSurfaces")
|
||||
adapter := methodCallPosition(sequence, "openStateStoreAdapter")
|
||||
wiring := methodCallPosition(sequence, "openDaemonWorkflowDefinitions")
|
||||
if wiring == token.NoPos {
|
||||
t.Fatal("openDaemonStateSurfaces never builds the daemon's workflow-definitions client; every task pin would fall back to the shipped definitions")
|
||||
}
|
||||
if adapter == token.NoPos || wiring < adapter {
|
||||
t.Errorf("openDaemonStateSurfaces builds the workflow-definitions client at %v, at or before openStateStoreAdapter at %v: it would wrap the transport the adapter has not opened yet", wiring, adapter)
|
||||
}
|
||||
}
|
||||
|
||||
func parsedBody(t *testing.T, file, function string) *ast.BlockStmt {
|
||||
t.Helper()
|
||||
parsed, err := parser.ParseFile(token.NewFileSet(), file, nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return methodBody(t, parsed, function)
|
||||
}
|
||||
|
||||
// stepVocabularyAssignment returns the identifier assigned from a direct call
|
||||
// to stepVocabulary() in body, or "" when body never calls it.
|
||||
func stepVocabularyAssignment(body *ast.BlockStmt) string {
|
||||
manager := ""
|
||||
ast.Inspect(body, func(node ast.Node) bool {
|
||||
assign, ok := node.(*ast.AssignStmt)
|
||||
if !ok || len(assign.Lhs) == 0 || len(assign.Rhs) == 0 || manager != "" {
|
||||
return true
|
||||
}
|
||||
call, ok := assign.Rhs[0].(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
callee, ok := call.Fun.(*ast.Ident)
|
||||
if !ok || callee.Name != "stepVocabulary" {
|
||||
return true
|
||||
}
|
||||
if lhs, ok := assign.Lhs[0].(*ast.Ident); ok {
|
||||
manager = lhs.Name
|
||||
}
|
||||
return true
|
||||
})
|
||||
return manager
|
||||
}
|
||||
|
||||
// callPassesIdent reports whether some call to name (bare or selected) passes an
|
||||
// identifier called ident as an argument.
|
||||
func callPassesIdent(body *ast.BlockStmt, name, ident string) bool {
|
||||
found := false
|
||||
ast.Inspect(body, func(node ast.Node) bool {
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok || !callNameIs(call, name) {
|
||||
return true
|
||||
}
|
||||
for _, argument := range call.Args {
|
||||
if passed, ok := argument.(*ast.Ident); ok && passed.Name == ident {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
return found
|
||||
}
|
||||
|
||||
func callNameIs(call *ast.CallExpr, name string) bool {
|
||||
switch fun := call.Fun.(type) {
|
||||
case *ast.Ident:
|
||||
return fun.Name == name
|
||||
case *ast.SelectorExpr:
|
||||
return fun.Sel.Name == name
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// fileMentionsIdent reports whether any declaration in file names ident.
|
||||
func fileMentionsIdent(t *testing.T, file, ident string) bool {
|
||||
t.Helper()
|
||||
parsed, err := parser.ParseFile(token.NewFileSet(), file, nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mentions := false
|
||||
ast.Inspect(parsed, func(node ast.Node) bool {
|
||||
if found, ok := node.(*ast.Ident); ok && found.Name == ident {
|
||||
mentions = true
|
||||
}
|
||||
return true
|
||||
})
|
||||
return mentions
|
||||
}
|
||||
|
||||
// identCallPosition returns the position of the first call to a bare function
|
||||
// name in body, or token.NoPos when the body never calls it.
|
||||
func identCallPosition(body *ast.BlockStmt, name string) token.Pos {
|
||||
position := token.NoPos
|
||||
ast.Inspect(body, func(node ast.Node) bool {
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
ident, ok := call.Fun.(*ast.Ident)
|
||||
if ok && ident.Name == name && position == token.NoPos {
|
||||
position = call.Pos()
|
||||
}
|
||||
return true
|
||||
})
|
||||
return position
|
||||
}
|
||||
@@ -1,299 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate/taskstatetest"
|
||||
)
|
||||
|
||||
// testTaskActor formats taskactions.Service's result the same way the real
|
||||
// NATS actor (infrastructure/taskactions.Client) does, so this test exercises
|
||||
// the shared service through the same chatTaskActorAdapter → LocalChatAdapter
|
||||
// → ChatTaskActor chain production traffic uses.
|
||||
type testTaskActor struct{ b *boot }
|
||||
|
||||
func (a testTaskActor) ApplyChatTaskAction(
|
||||
ctx context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action, res taskactions.ActionPayload,
|
||||
) (gateway.TaskActionResult, error) {
|
||||
if err := a.b.taskActions().Apply(ctx, identity, actor, taskID, action, res); err != nil {
|
||||
return gateway.TaskActionResult{}, err
|
||||
}
|
||||
return gateway.TaskActionResult{
|
||||
TaskID: taskID,
|
||||
Action: string(action),
|
||||
Message: fmt.Sprintf("Applied %s to task %d.", action, taskID),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func newChatTaskActorForTest(t *testing.T, st storecontract.TaskStore, cfg config.Config) chatTaskActorAdapter {
|
||||
t.Helper()
|
||||
b := &boot{
|
||||
st: st,
|
||||
stateStore: st,
|
||||
cfg: cfg,
|
||||
log: slog.Default(),
|
||||
}
|
||||
return chatTaskActorAdapter{contract: &gateway.LocalChatAdapter{TaskActor: testTaskActor{b}}}
|
||||
}
|
||||
|
||||
func TestChatTaskActorAdapterCrossIdentityRefused(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "parked job", "", "", "identity-owner", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
taskstatetest.Seed(ctx, t, st, task.ID, workflow.StatusQueued, workflow.StatusParked, "needs help")
|
||||
|
||||
adapter := newChatTaskActorForTest(t, st, config.Config{})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
actorIdentity string
|
||||
action taskstate.Action
|
||||
}{
|
||||
{
|
||||
name: "different identity cannot abandon",
|
||||
actorIdentity: "identity-attacker",
|
||||
action: taskstate.ActionAbandon,
|
||||
},
|
||||
{
|
||||
name: "different identity cannot retry",
|
||||
actorIdentity: "identity-attacker",
|
||||
action: taskstate.ActionRetry,
|
||||
},
|
||||
{
|
||||
name: "different identity cannot archive",
|
||||
actorIdentity: "identity-attacker",
|
||||
action: taskstate.ActionArchive,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, err := adapter.ApplyChatTaskAction(ctx, &tc.actorIdentity, taskactions.Actor{}, task.ID, tc.action, taskactions.ActionPayload{})
|
||||
if err == nil {
|
||||
t.Fatalf("ApplyChatTaskAction() allowed cross-identity action %s by %q on task owned by %q",
|
||||
tc.action, tc.actorIdentity, task.Identity)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "identity-owner") || !strings.Contains(err.Error(), tc.actorIdentity) {
|
||||
t.Errorf("error = %q, want mention of both identities", err.Error())
|
||||
}
|
||||
|
||||
// Confirm store state was NOT mutated.
|
||||
current, err := st.TaskByID(ctx, task.ID)
|
||||
if err != nil || current == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", current, err)
|
||||
}
|
||||
if current.Status != workflow.StatusParked {
|
||||
t.Errorf("task status mutated to %q despite cross-identity refusal", current.Status)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatTaskActorAdapterRefusesDisallowedStateAction(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
adapter := newChatTaskActorForTest(t, st, config.Config{})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
initialStatus string
|
||||
attemptAction taskstate.Action
|
||||
}{
|
||||
{
|
||||
name: "cannot abandon running task",
|
||||
initialStatus: workflow.StatusRunning,
|
||||
attemptAction: taskstate.ActionAbandon,
|
||||
},
|
||||
{
|
||||
name: "cannot archive parked task",
|
||||
initialStatus: workflow.StatusParked,
|
||||
attemptAction: taskstate.ActionArchive,
|
||||
},
|
||||
{
|
||||
name: "cannot retry queued task",
|
||||
initialStatus: workflow.StatusQueued,
|
||||
attemptAction: taskstate.ActionRetry,
|
||||
},
|
||||
{
|
||||
name: "cannot approve running task",
|
||||
initialStatus: workflow.StatusRunning,
|
||||
attemptAction: taskstate.ActionApprove,
|
||||
},
|
||||
{
|
||||
name: "cannot reject merged task",
|
||||
initialStatus: workflow.StatusMerged,
|
||||
attemptAction: taskstate.ActionReject,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "test task", "", "", "archie", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
taskstatetest.Seed(ctx, t, st, task.ID, workflow.StatusQueued, tc.initialStatus, "setup")
|
||||
|
||||
_, err = adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, task.ID, tc.attemptAction, taskactions.ActionPayload{})
|
||||
if err == nil {
|
||||
t.Fatalf("expected error attempting %s on %s task, got nil", tc.attemptAction, tc.initialStatus)
|
||||
}
|
||||
|
||||
// Assert error matches taskstate rules.
|
||||
wantErr := taskstate.CheckAction(tc.initialStatus, tc.attemptAction)
|
||||
if wantErr != nil && !strings.Contains(err.Error(), wantErr.Error()) {
|
||||
t.Errorf("error = %q, want substring %q", err.Error(), wantErr.Error())
|
||||
}
|
||||
|
||||
// Ensure task status did not change.
|
||||
current, err := st.TaskByID(ctx, task.ID)
|
||||
if err != nil || current == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", current, err)
|
||||
}
|
||||
if current.Status != tc.initialStatus {
|
||||
t.Errorf("task status changed to %q, want %q", current.Status, tc.initialStatus)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatTaskActorAdapterTaskNotFound(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
adapter := newChatTaskActorForTest(t, st, config.Config{})
|
||||
|
||||
_, err := adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, 999999, taskstate.ActionAbandon, taskactions.ActionPayload{})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for non-existent task, got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "not found") {
|
||||
t.Errorf("error = %q, want 'not found'", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatTaskActorAdapterAppliesActionsToStore(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
initialStatus string
|
||||
action taskstate.Action
|
||||
wantStatus string
|
||||
wantArchived bool
|
||||
}{
|
||||
{
|
||||
name: "abandon parked task closes it won't do",
|
||||
initialStatus: workflow.StatusParked,
|
||||
action: taskstate.ActionAbandon,
|
||||
wantStatus: workflow.StatusClosedWontDo,
|
||||
},
|
||||
{
|
||||
name: "retry parked task requeues it",
|
||||
initialStatus: workflow.StatusParked,
|
||||
action: taskstate.ActionRetry,
|
||||
wantStatus: workflow.StatusQueued,
|
||||
},
|
||||
{
|
||||
name: "cancel queued task closes it",
|
||||
initialStatus: workflow.StatusQueued,
|
||||
action: taskstate.ActionCancel,
|
||||
wantStatus: workflow.StatusClosedWontDo,
|
||||
},
|
||||
{
|
||||
name: "approve waiting_human task queues it",
|
||||
initialStatus: workflow.StatusWaitingHuman,
|
||||
action: taskstate.ActionApprove,
|
||||
wantStatus: workflow.StatusQueued,
|
||||
},
|
||||
{
|
||||
name: "reject waiting_human task closes it",
|
||||
initialStatus: workflow.StatusWaitingHuman,
|
||||
action: taskstate.ActionReject,
|
||||
wantStatus: workflow.StatusClosedWontDo,
|
||||
},
|
||||
{
|
||||
name: "archive dead task removes it from store",
|
||||
initialStatus: workflow.StatusDead,
|
||||
action: taskstate.ActionArchive,
|
||||
wantArchived: true,
|
||||
},
|
||||
{
|
||||
name: "archive closed_wont_do task removes it from store",
|
||||
initialStatus: workflow.StatusClosedWontDo,
|
||||
action: taskstate.ActionArchive,
|
||||
wantArchived: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
adapter := newChatTaskActorForTest(t, st, config.Config{MaxRetries: 3})
|
||||
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "actionable task", "", "", "archie", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
taskstatetest.Seed(ctx, t, st, task.ID, workflow.StatusQueued, tc.initialStatus, "setup")
|
||||
|
||||
result, err := adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, task.ID, tc.action, taskactions.ActionPayload{})
|
||||
if err != nil {
|
||||
t.Fatalf("ApplyChatTaskAction(%s) error = %v", tc.action, err)
|
||||
}
|
||||
if result.TaskID != task.ID {
|
||||
t.Errorf("result.TaskID = %d, want %d", result.TaskID, task.ID)
|
||||
}
|
||||
if result.Action != string(tc.action) {
|
||||
t.Errorf("result.Action = %q, want %q", result.Action, tc.action)
|
||||
}
|
||||
|
||||
current, err := st.TaskByID(ctx, task.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tc.wantArchived {
|
||||
if current != nil {
|
||||
t.Errorf("task %d still exists in store after archive: %+v", task.ID, current)
|
||||
}
|
||||
} else {
|
||||
if current == nil {
|
||||
t.Fatalf("task %d not found in store", task.ID)
|
||||
}
|
||||
if current.Status != tc.wantStatus {
|
||||
t.Errorf("task status = %q, want %q", current.Status, tc.wantStatus)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatTaskActorAdapterNilContract(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
adapter := chatTaskActorAdapter{contract: nil}
|
||||
|
||||
_, err := adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, 1, taskstate.ActionAbandon, taskactions.ActionPayload{})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for nil contract, got nil")
|
||||
}
|
||||
}
|
||||
@@ -1,136 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
taskactionstore "github.com/samcharles93/archie-core/internal/infrastructure/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate/taskstatetest"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
|
||||
// The dashboard and chat both let an operator approve or decline a task, and
|
||||
// they had drifted: declining from the dashboard left the task
|
||||
// closed_wont_do, cancelling the same task from chat left it rejected. Two
|
||||
// operators looking at one queue saw different states for the same decision,
|
||||
// and "rejected" -- which reconcilePRs uses for a pull request closed without
|
||||
// merging -- no longer meant one thing.
|
||||
//
|
||||
// This drives both real surfaces against one store and asserts they agree.
|
||||
// It lives in cmd/archied because that is the only place both are wired.
|
||||
func TestDashboardAndChatAgreeOnTerminalStates(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
// viaChat runs the action through the chat router; otherwise it
|
||||
// goes through the dashboard's HTTP handler.
|
||||
viaChat bool
|
||||
action string
|
||||
want string
|
||||
}{
|
||||
{name: "dashboard reject", action: "reject", want: workflow.StatusClosedWontDo},
|
||||
{name: "chat cancel", viaChat: true, action: "cancel", want: workflow.StatusClosedWontDo},
|
||||
{name: "dashboard approve", action: "approve", want: workflow.StatusQueued},
|
||||
{name: "chat approve", viaChat: true, action: "approve", want: workflow.StatusQueued},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "decide on me", "", "", "reviewer", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
taskstatetest.Seed(ctx, t, st, task.ID, workflow.StatusQueued, workflow.StatusWaitingHuman, "await")
|
||||
|
||||
if tc.viaChat {
|
||||
runChatAction(t, ctx, st, tc.action, task.ID)
|
||||
} else {
|
||||
runDashboardAction(t, ctx, st, tc.action, task.ID)
|
||||
}
|
||||
|
||||
got, err := st.TaskByID(ctx, task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", got, err)
|
||||
}
|
||||
if got.Status != tc.want {
|
||||
t.Errorf("status = %q, want %q: the two surfaces disagree about "+
|
||||
"what this action means", got.Status, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// runChatAction performs the approve/cancel action through the chat
|
||||
// controller path and fails the test on error.
|
||||
func runChatAction(t *testing.T, ctx context.Context, st storecontract.TaskStore, action string, taskID int64) {
|
||||
t.Helper()
|
||||
canceller, ok := st.(storecontract.ExecutionCanceller)
|
||||
if !ok {
|
||||
t.Fatal("the task store cannot cancel executions")
|
||||
}
|
||||
// Chat's /approve reaches the daemon's one task-action service
|
||||
// (docs/prds/pr-review-operator-response.md, Decision 1).
|
||||
actions := taskactionstore.NewService(taskactionstore.Store{TaskStore: st}, nil, nil, nil, nil, nil, nil, nil)
|
||||
controller := gateway.NewStoreTaskController(chatTaskControllerAdapter{
|
||||
taskByID: st.TaskByID,
|
||||
approve: func(ctx context.Context, scope *string, actor taskactions.Actor, taskID int64, res taskactions.ActionPayload) error {
|
||||
return actions.Apply(ctx, scope, actor, taskID, taskstate.ActionApprove, res)
|
||||
},
|
||||
cancelExecution: canceller.CancelExecution,
|
||||
})
|
||||
var err error
|
||||
if action == "approve" {
|
||||
err = controller.Approve(ctx, taskID, "reviewer")
|
||||
} else {
|
||||
err = controller.Cancel(ctx, taskID, "reviewer")
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("chat %s: %v", action, err)
|
||||
}
|
||||
}
|
||||
|
||||
// runDashboardAction performs the approve/cancel action through the
|
||||
// dashboard's HTTP handler and fails the test when the request is
|
||||
// rejected.
|
||||
func runDashboardAction(t *testing.T, ctx context.Context, st storecontract.TaskStore, action string, taskID int64) {
|
||||
t.Helper()
|
||||
// The dashboard reaches task actions through the Gateway contract, which
|
||||
// in production carries them back to this daemon's own service. Wiring
|
||||
// that service behind a local adapter keeps both surfaces in this test
|
||||
// driving the one implementation, which is the whole point of it.
|
||||
actor := testTaskActor{&boot{
|
||||
st: st, stateStore: st,
|
||||
cfg: config.Config{MaxRetries: 3},
|
||||
cfgHolder: config.NewHolder(config.Config{MaxRetries: 3}),
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
}}
|
||||
srv := &webui.Server{
|
||||
Store: st,
|
||||
Chat: &webui.ChatService{Contract: &gateway.LocalChatAdapter{TaskActor: actor}},
|
||||
}
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodPost,
|
||||
"/api/tasks/"+strconv.FormatInt(taskID, 10)+"/action",
|
||||
bytes.NewBufferString(`{"action":"`+action+`"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Archie-CSRF", "1")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("dashboard %s: status %d, body %s", action, w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
@@ -1,337 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/plugin"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
toolprovider "github.com/samcharles93/archie-core/internal/tools/provider"
|
||||
"github.com/samcharles93/archie-core/internal/tools/webfetch"
|
||||
)
|
||||
|
||||
// fakeMCPEngine stands in for a configured MCP server so the live reconciliation
|
||||
// can be driven without spawning a process. It records each lifecycle call on
|
||||
// the shared recorder, keyed by configured server name.
|
||||
type fakeMCPEngine struct {
|
||||
name string
|
||||
tools []tools.ToolEntry
|
||||
rec *mcpEngineRecorder
|
||||
startErr error
|
||||
}
|
||||
|
||||
func (e *fakeMCPEngine) Manifest() plugin.Manifest {
|
||||
return plugin.Manifest{
|
||||
ID: "mcp." + e.name,
|
||||
Name: e.name,
|
||||
Version: "1.0.0",
|
||||
APIVersion: plugin.HostAPIVersion,
|
||||
Capabilities: []plugin.CapabilityKind{"tools"},
|
||||
}
|
||||
}
|
||||
|
||||
func (e *fakeMCPEngine) Start(context.Context) error {
|
||||
e.rec.recordStart(e.name)
|
||||
return e.startErr
|
||||
}
|
||||
|
||||
func (e *fakeMCPEngine) Stop(context.Context) error {
|
||||
e.rec.recordStop(e.name)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *fakeMCPEngine) Discover(context.Context) ([]tools.ToolEntry, error) {
|
||||
return append([]tools.ToolEntry(nil), e.tools...), nil
|
||||
}
|
||||
|
||||
// mcpEngineRecorder records what the live reconciliation did to each server and
|
||||
// hands the test a factory boot.mcpProvider can use.
|
||||
type mcpEngineRecorder struct {
|
||||
mu sync.Mutex
|
||||
builds map[string]int
|
||||
starts map[string]int
|
||||
stops map[string]int
|
||||
failNext map[string]error
|
||||
seen map[string]config.MCPServer
|
||||
}
|
||||
|
||||
func newMCPEngineRecorder() *mcpEngineRecorder {
|
||||
return &mcpEngineRecorder{
|
||||
builds: map[string]int{},
|
||||
starts: map[string]int{},
|
||||
stops: map[string]int{},
|
||||
failNext: map[string]error{},
|
||||
seen: map[string]config.MCPServer{},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *mcpEngineRecorder) factory() func(config.MCPServer) (toolprovider.Engine, error) {
|
||||
return func(srv config.MCPServer) (toolprovider.Engine, error) {
|
||||
name := strings.TrimSpace(srv.Name)
|
||||
r.mu.Lock()
|
||||
r.builds[name]++
|
||||
r.seen[name] = srv
|
||||
err := r.failNext[name]
|
||||
delete(r.failNext, name)
|
||||
r.mu.Unlock()
|
||||
return &fakeMCPEngine{
|
||||
name: name,
|
||||
rec: r,
|
||||
startErr: err,
|
||||
tools: []tools.ToolEntry{{
|
||||
Name: "mcp." + name + ".tool",
|
||||
Toolset: "mcp",
|
||||
Handler: func(context.Context, map[string]any) (any, error) { return "ok", nil },
|
||||
}},
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (r *mcpEngineRecorder) recordStart(name string) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.starts[name]++
|
||||
}
|
||||
|
||||
func (r *mcpEngineRecorder) recordStop(name string) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.stops[name]++
|
||||
}
|
||||
|
||||
func (r *mcpEngineRecorder) failOnNextStart(name string, err error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.failNext[name] = err
|
||||
}
|
||||
|
||||
func (r *mcpEngineRecorder) count(counts map[string]int, name string) int {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return counts[name]
|
||||
}
|
||||
|
||||
// toolSettingsDocument renders a stored tool-settings document carrying the
|
||||
// given MCP servers and an enabled web_fetch.
|
||||
func toolSettingsDocument(servers ...map[string]any) map[string]any {
|
||||
return map[string]any{
|
||||
"mcp_servers": servers,
|
||||
"policy": map[string]any{},
|
||||
"web_fetch": map[string]any{},
|
||||
"minimax": map[string]any{},
|
||||
}
|
||||
}
|
||||
|
||||
func mcpServerDoc(name string, parallel bool) map[string]any {
|
||||
return map[string]any{
|
||||
"name": name,
|
||||
"transport": "stdio",
|
||||
"command": "run-server",
|
||||
"parallel_tool_calls": parallel,
|
||||
}
|
||||
}
|
||||
|
||||
// newMCPReconcileBoot builds a boot whose provider registry is running, so the
|
||||
// live reconciliation acts on a real registry and a real tool index.
|
||||
func newMCPReconcileBoot(t *testing.T, base config.Config, stub *resourceWatchStub) (*boot, *applyStatusRecorder, *mcpEngineRecorder) {
|
||||
t.Helper()
|
||||
b, status := newLiveApplyBoot(t, base)
|
||||
b.controlPlane = controlplane.NewRPCClient(stub)
|
||||
b.secrets = secret.NewRegistry()
|
||||
b.toolReg = tools.NewRegistry()
|
||||
b.providerRegistry = toolprovider.NewRegistry(b.toolReg)
|
||||
if err := b.providerRegistry.Start(t.Context()); err != nil {
|
||||
t.Fatalf("start provider registry: %v", err)
|
||||
}
|
||||
b.mcpApplied = map[string]appliedMCPServer{}
|
||||
rec := newMCPEngineRecorder()
|
||||
b.mcpProvider = rec.factory()
|
||||
return b, status, rec
|
||||
}
|
||||
|
||||
// applyToolSettings stores the document and runs the live apply the watch
|
||||
// would run, the seam the daemon meets a stored tool-settings change through.
|
||||
func applyToolSettings(t *testing.T, b *boot, stub *resourceWatchStub, version int64, document map[string]any) {
|
||||
t.Helper()
|
||||
if stub.values == nil {
|
||||
stub.values = map[string]any{}
|
||||
}
|
||||
stub.values[controlplane.ToolSettingsKind] = document
|
||||
if stub.storedVersion == nil {
|
||||
stub.storedVersion = map[string]int64{}
|
||||
}
|
||||
stub.storedVersion[controlplane.ToolSettingsKind] = version
|
||||
b.applyRuntimeResourceUpdate(t.Context(), controlplane.ToolSettingsKind, controlplane.AppliedResource{Version: version})
|
||||
}
|
||||
|
||||
func TestLiveToolSettingsConnectsAnAddedServer(t *testing.T) {
|
||||
stub := &resourceWatchStub{values: databaseOwnedResources(), version: 10, storedVersion: map[string]int64{}, opens: map[string]int{}}
|
||||
b, _, rec := newMCPReconcileBoot(t, fileConfig(), stub)
|
||||
|
||||
applyToolSettings(t, b, stub, 11, toolSettingsDocument(mcpServerDoc("alpha", false)))
|
||||
|
||||
if got := rec.count(rec.starts, "alpha"); got != 1 {
|
||||
t.Errorf("alpha start count = %d, want 1", got)
|
||||
}
|
||||
if _, ok := b.toolReg.Get("mcp.alpha.tool"); !ok {
|
||||
t.Error("the added server's tool was not indexed")
|
||||
}
|
||||
if !b.providerRegistry.Has("mcp.alpha") {
|
||||
t.Error("the added server is not registered")
|
||||
}
|
||||
servers := b.cfgHolder.Get().Tools.MCPServers
|
||||
if len(servers) != 1 || servers[0].Name != "alpha" {
|
||||
t.Errorf("running config servers = %+v, want the added alpha", servers)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveToolSettingsLeavesAnUnchangedServerUntouched(t *testing.T) {
|
||||
stub := &resourceWatchStub{values: databaseOwnedResources(), version: 10, storedVersion: map[string]int64{}, opens: map[string]int{}}
|
||||
b, _, rec := newMCPReconcileBoot(t, fileConfig(), stub)
|
||||
|
||||
applyToolSettings(t, b, stub, 11, toolSettingsDocument(mcpServerDoc("alpha", false)))
|
||||
applyToolSettings(t, b, stub, 12, toolSettingsDocument(mcpServerDoc("alpha", false), mcpServerDoc("beta", false)))
|
||||
|
||||
if got := rec.count(rec.builds, "alpha"); got != 1 {
|
||||
t.Errorf("alpha was rebuilt on an unchanged update: builds = %d, want 1", got)
|
||||
}
|
||||
if got := rec.count(rec.starts, "alpha"); got != 1 {
|
||||
t.Errorf("alpha was reconnected on an unchanged update: starts = %d, want 1", got)
|
||||
}
|
||||
if got := rec.count(rec.stops, "alpha"); got != 0 {
|
||||
t.Errorf("alpha was stopped on an unchanged update: stops = %d, want 0", got)
|
||||
}
|
||||
if got := rec.count(rec.starts, "beta"); got != 1 {
|
||||
t.Errorf("beta start count = %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveToolSettingsReconnectsAChangedServer(t *testing.T) {
|
||||
stub := &resourceWatchStub{values: databaseOwnedResources(), version: 10, storedVersion: map[string]int64{}, opens: map[string]int{}}
|
||||
b, _, rec := newMCPReconcileBoot(t, fileConfig(), stub)
|
||||
|
||||
applyToolSettings(t, b, stub, 11, toolSettingsDocument(mcpServerDoc("alpha", false)))
|
||||
applyToolSettings(t, b, stub, 12, toolSettingsDocument(mcpServerDoc("alpha", true)))
|
||||
|
||||
if got := rec.count(rec.stops, "alpha"); got != 1 {
|
||||
t.Errorf("the changed server was not disconnected: stops = %d, want 1", got)
|
||||
}
|
||||
if got := rec.count(rec.starts, "alpha"); got != 2 {
|
||||
t.Errorf("the changed server was not reconnected: starts = %d, want 2", got)
|
||||
}
|
||||
if _, ok := b.toolReg.Get("mcp.alpha.tool"); !ok {
|
||||
t.Error("the reconnected server's tool left the index")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveToolSettingsDisconnectsARemovedServer(t *testing.T) {
|
||||
stub := &resourceWatchStub{values: databaseOwnedResources(), version: 10, storedVersion: map[string]int64{}, opens: map[string]int{}}
|
||||
b, _, rec := newMCPReconcileBoot(t, fileConfig(), stub)
|
||||
|
||||
applyToolSettings(t, b, stub, 11, toolSettingsDocument(mcpServerDoc("alpha", false), mcpServerDoc("beta", false)))
|
||||
applyToolSettings(t, b, stub, 12, toolSettingsDocument(mcpServerDoc("beta", false)))
|
||||
|
||||
if got := rec.count(rec.stops, "alpha"); got != 1 {
|
||||
t.Errorf("the removed server was not disconnected: stops = %d, want 1", got)
|
||||
}
|
||||
if b.providerRegistry.Has("mcp.alpha") {
|
||||
t.Error("the removed server stayed registered")
|
||||
}
|
||||
if _, ok := b.toolReg.Get("mcp.alpha.tool"); ok {
|
||||
t.Error("the removed server's tool stayed indexed")
|
||||
}
|
||||
if got := rec.count(rec.stops, "beta"); got != 0 {
|
||||
t.Errorf("the surviving server was disturbed: stops = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLiveToolSettingsKeepsTheRunningServerWhenAChangeCannotStart is the path
|
||||
// where the change must NOT apply: a changed server whose replacement fails to
|
||||
// start is rolled back to the one that was running, and the refusal reaches
|
||||
// apply status rather than the kind silently reporting success.
|
||||
func TestLiveToolSettingsKeepsTheRunningServerWhenAChangeCannotStart(t *testing.T) {
|
||||
stub := &resourceWatchStub{values: databaseOwnedResources(), version: 10, storedVersion: map[string]int64{}, opens: map[string]int{}}
|
||||
b, status, rec := newMCPReconcileBoot(t, fileConfig(), stub)
|
||||
|
||||
applyToolSettings(t, b, stub, 11, toolSettingsDocument(mcpServerDoc("alpha", false)))
|
||||
rec.failOnNextStart("alpha", errors.New("handshake refused"))
|
||||
applyToolSettings(t, b, stub, 12, toolSettingsDocument(mcpServerDoc("alpha", true)))
|
||||
|
||||
// Two stops: the running server is disconnected for the replacement, and
|
||||
// the replacement's own half-start is cleaned up when its handshake fails.
|
||||
if got := rec.count(rec.stops, "alpha"); got != 2 {
|
||||
t.Errorf("stops = %d, want 2 (the replaced server and the failed replacement's cleanup)", got)
|
||||
}
|
||||
if got := rec.count(rec.starts, "alpha"); got != 3 {
|
||||
t.Errorf("starts = %d, want 3 (initial, refused replacement, rollback restart)", got)
|
||||
}
|
||||
if _, ok := b.toolReg.Get("mcp.alpha.tool"); !ok {
|
||||
t.Error("the refused change left the running server's tool out of the index")
|
||||
}
|
||||
if !b.providerRegistry.Has("mcp.alpha") {
|
||||
t.Error("the refused change left the server unregistered")
|
||||
}
|
||||
last, ok := status.last(controlplane.ToolSettingsKind)
|
||||
if !ok {
|
||||
t.Fatal("the refused change reported no apply status")
|
||||
}
|
||||
if !strings.Contains(last.Error, "alpha") {
|
||||
t.Errorf("apply status error = %q, want it to name the refused server", last.Error)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLiveToolSettingsRebuildsTheWebFetchEntry: web_fetch captured its config
|
||||
// at construction, so a live change rebuilds the entry rather than leaving the
|
||||
// boot value in the model's tool list.
|
||||
func TestLiveToolSettingsRebuildsTheWebFetchEntry(t *testing.T) {
|
||||
stub := &resourceWatchStub{values: databaseOwnedResources(), version: 10, storedVersion: map[string]int64{}, opens: map[string]int{}}
|
||||
b, _, _ := newMCPReconcileBoot(t, fileConfig(), stub)
|
||||
|
||||
disabled := toolSettingsDocument()
|
||||
disabled["web_fetch"] = map[string]any{"enabled": false}
|
||||
applyToolSettings(t, b, stub, 11, disabled)
|
||||
if _, ok := b.toolReg.Get(webfetch.ToolName); ok {
|
||||
t.Error("web_fetch stayed registered after the stored document disabled it")
|
||||
}
|
||||
|
||||
applyToolSettings(t, b, stub, 12, toolSettingsDocument())
|
||||
if _, ok := b.toolReg.Get(webfetch.ToolName); !ok {
|
||||
t.Error("web_fetch was not registered after the stored document re-enabled it")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLiveToolSettingsKeepsAnUnprojectedMCPHeader: the stored document cannot
|
||||
// carry secret-bearing headers, so the layering restores them from the running
|
||||
// base (controlplane.runtimeToolConfigFrom). The reconciliation must build the
|
||||
// reconnected engine from that layered server, not from the document alone, or
|
||||
// an authentication header disappears on the first live edit.
|
||||
func TestLiveToolSettingsKeepsAnUnprojectedMCPHeader(t *testing.T) {
|
||||
base := fileConfig()
|
||||
base.Tools.MCPServers = []config.MCPServer{{
|
||||
Name: "alpha",
|
||||
Transport: "http",
|
||||
URL: "https://alpha.example/mcp",
|
||||
Headers: map[string]string{"Authorization": "Bearer secret"},
|
||||
}}
|
||||
stub := &resourceWatchStub{values: databaseOwnedResources(), version: 10, storedVersion: map[string]int64{}, opens: map[string]int{}}
|
||||
b, _, rec := newMCPReconcileBoot(t, base, stub)
|
||||
|
||||
changed := mcpServerDoc("alpha", true)
|
||||
changed["transport"] = "http"
|
||||
changed["url"] = "https://alpha.example/mcp"
|
||||
delete(changed, "command")
|
||||
applyToolSettings(t, b, stub, 11, toolSettingsDocument(changed))
|
||||
|
||||
rec.mu.Lock()
|
||||
seen := rec.seen["alpha"]
|
||||
rec.mu.Unlock()
|
||||
if got := seen.Headers["Authorization"]; got != "Bearer secret" {
|
||||
t.Errorf("reconnected server headers = %v, want the unprojected Authorization header restored", seen.Headers)
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
aicore "github.com/samcharles93/ai-sdk/core"
|
||||
)
|
||||
|
||||
func TestToolSummaries(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
set aicore.ToolSet
|
||||
want []string // expected "name: description" pairs, in order
|
||||
}{
|
||||
{
|
||||
name: "nil set yields no summaries",
|
||||
set: nil,
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "empty set yields no summaries",
|
||||
set: aicore.ToolSet{},
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "summaries are sorted by name for a stable prompt",
|
||||
set: aicore.ToolSet{
|
||||
"skill_activate": aicore.NewTool("skill_activate", "Load a skill", nil, nil),
|
||||
"memory_edit": aicore.NewTool("memory_edit", "Edit memory", nil, nil),
|
||||
},
|
||||
// ToolSet is a map: without sorting the prompt text would
|
||||
// differ between turns and defeat provider prompt caching.
|
||||
want: []string{"memory_edit: Edit memory", "skill_activate: Load a skill"},
|
||||
},
|
||||
{
|
||||
name: "nil entries are skipped rather than panicking",
|
||||
set: aicore.ToolSet{"broken": nil},
|
||||
want: nil,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := toolSummaries(tc.set)
|
||||
if len(got) != len(tc.want) {
|
||||
t.Fatalf("toolSummaries() returned %d summaries, want %d: %+v", len(got), len(tc.want), got)
|
||||
}
|
||||
for i, want := range tc.want {
|
||||
joined := got[i].Name + ": " + got[i].Description
|
||||
if joined != want {
|
||||
t.Errorf("summary %d = %q, want %q", i, joined, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/transcription"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
// TestSetupTranscriberBuildsOnTheModelOwningSide pins where the voice
|
||||
// capability is constructed: beside the chat runtime, from the process's own
|
||||
// [models].transcription and [providers.*]. The Messaging Service carries the
|
||||
// audio bytes across the inbound wire but no longer builds this client.
|
||||
func TestSetupTranscriberBuildsOnTheModelOwningSide(t *testing.T) {
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
|
||||
t.Run("configured role wires a transcriber", func(t *testing.T) {
|
||||
b := &boot{secrets: secret.NewRegistry()}
|
||||
b.setupTranscriber(config.Config{
|
||||
Models: map[string]string{transcription.Role: "local/whisper-large-v3"},
|
||||
Providers: map[string]config.Provider{
|
||||
"local": {Class: "openai-compatible", BaseURL: "http://127.0.0.1:8080/v1"},
|
||||
},
|
||||
}, log)
|
||||
if b.transcriber == nil {
|
||||
t.Fatal("transcriber = nil, want a client built from [models].transcription")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("absent role degrades to nil", func(t *testing.T) {
|
||||
b := &boot{secrets: secret.NewRegistry()}
|
||||
b.setupTranscriber(config.Config{}, log)
|
||||
if b.transcriber != nil {
|
||||
t.Fatalf("transcriber = %v, want nil when no role is configured", b.transcriber)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestLoadConfigWarnsOnUnknownKeys pins plan-config-drift.md step 3: a
|
||||
// stray/misspelled config key must be visible to the operator, not just
|
||||
// silently parsed, validated and dropped.
|
||||
func TestLoadConfigWarnsOnUnknownKeys(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
writeConfig(t, path, minimalConfigTOML("widget")+"[containers]\nmax_concurrancy = 4\n")
|
||||
|
||||
var sb strings.Builder
|
||||
log := slog.New(slog.NewTextHandler(&sb, &slog.HandlerOptions{Level: slog.LevelWarn}))
|
||||
b := &boot{log: log}
|
||||
|
||||
if err := b.loadConfig(t.Context(), path, ""); err != nil {
|
||||
t.Fatalf("loadConfig: %v (an unknown key must not fail the boot)", err)
|
||||
}
|
||||
|
||||
out := sb.String()
|
||||
if !strings.Contains(out, "containers.max_concurrancy") {
|
||||
t.Errorf("log does not name the unknown key: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadConfigDoesNotWarnOnAKnownConfig is the negative case: a config
|
||||
// with no unknown keys must produce no warning, so the new check cannot
|
||||
// itself become log noise for a working deployment.
|
||||
func TestLoadConfigDoesNotWarnOnAKnownConfig(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
writeConfig(t, path, minimalConfigTOML("widget"))
|
||||
|
||||
var sb strings.Builder
|
||||
log := slog.New(slog.NewTextHandler(&sb, &slog.HandlerOptions{Level: slog.LevelWarn}))
|
||||
b := &boot{log: log}
|
||||
|
||||
if err := b.loadConfig(t.Context(), path, ""); err != nil {
|
||||
t.Fatalf("loadConfig: %v", err)
|
||||
}
|
||||
|
||||
if out := sb.String(); strings.Contains(out, "unrecognised") || strings.Contains(out, "unknown") {
|
||||
t.Errorf("unexpected warning for a config with no unknown keys: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadConfigMakesRuntimeSettingsAvailableBeforeSubsystemSetup(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
writeConfig(t, path, minimalConfigTOML("widget"))
|
||||
b := &boot{log: slog.Default()}
|
||||
|
||||
if err := b.loadConfig(t.Context(), path, ""); err != nil {
|
||||
t.Fatalf("loadConfig: %v", err)
|
||||
}
|
||||
if b.cfgHolder == nil {
|
||||
t.Fatal("runtime config holder is nil before control-plane settings load")
|
||||
}
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
||||
)
|
||||
|
||||
// relayBoot is the daemon reduced to what the relay needs: a bus to publish
|
||||
// on and a logger.
|
||||
func relayBoot(t *testing.T) (*boot, *events.Sub) {
|
||||
t.Helper()
|
||||
bus := events.NewBus()
|
||||
t.Cleanup(bus.Close)
|
||||
sub := bus.Subscribe(4)
|
||||
return &boot{bus: bus, log: slog.New(slog.DiscardHandler)}, sub
|
||||
}
|
||||
|
||||
func waitForEvent(t *testing.T, sub *events.Sub) (events.Event, bool) {
|
||||
t.Helper()
|
||||
select {
|
||||
case e := <-sub.C:
|
||||
return e, true
|
||||
case <-time.After(2 * time.Second):
|
||||
return events.Event{}, false
|
||||
}
|
||||
}
|
||||
|
||||
// TestRelayUpdateReportPublishesAndClears: the watchdog leaves its verdict in
|
||||
// a file on the daemon's host, so the daemon reads it and puts the outcome on
|
||||
// the activity stream. Relaying twice would tell the operator the same update
|
||||
// finished twice, so the report is cleared as soon as it is handled
|
||||
// (archie-core-nln7, rehomed by archie-core-8cda.5.4).
|
||||
func TestRelayUpdateReportPublishesAndClears(t *testing.T) {
|
||||
b, sub := relayBoot(t)
|
||||
path := filepath.Join(t.TempDir(), "update-report.json")
|
||||
report := releaseupdate.Report{
|
||||
Channel: "webui",
|
||||
Previous: map[string]string{releaseupdate.ComponentDaemon: "1.0.0"},
|
||||
Installed: map[string]string{releaseupdate.ComponentDaemon: "1.1.0"},
|
||||
HealthCheck: "passed",
|
||||
}
|
||||
if err := releaseupdate.WritePendingReport(path, report); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
b.relayUpdateReport(path)
|
||||
|
||||
e, ok := waitForEvent(t, sub)
|
||||
if !ok {
|
||||
t.Fatal("no event published for a pending update report")
|
||||
}
|
||||
if e.Kind != events.KindUpdateReport {
|
||||
t.Errorf("kind = %q, want %q", e.Kind, events.KindUpdateReport)
|
||||
}
|
||||
if e.Data["health_check"] != "passed" {
|
||||
t.Errorf("health_check = %v, want passed", e.Data["health_check"])
|
||||
}
|
||||
if _, found, err := releaseupdate.ReadPendingReport(path); err != nil || found {
|
||||
t.Errorf("report still present after relaying: found=%v err=%v", found, err)
|
||||
}
|
||||
|
||||
// A second pass has nothing left to relay.
|
||||
b.relayUpdateReport(path)
|
||||
if e, ok := waitForEventQuickly(sub); ok {
|
||||
t.Fatalf("a cleared report was relayed again: %+v", e)
|
||||
}
|
||||
}
|
||||
|
||||
func waitForEventQuickly(sub *events.Sub) (events.Event, bool) {
|
||||
select {
|
||||
case e := <-sub.C:
|
||||
return e, true
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
return events.Event{}, false
|
||||
}
|
||||
}
|
||||
|
||||
// TestRelayUpdateReportClearsUnreadableReport: a corrupt report must not jam
|
||||
// every future boot behind it.
|
||||
func TestRelayUpdateReportClearsUnreadableReport(t *testing.T) {
|
||||
b, _ := relayBoot(t)
|
||||
path := filepath.Join(t.TempDir(), "update-report.json")
|
||||
if err := os.WriteFile(path, []byte("{not valid json"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
b.relayUpdateReport(path)
|
||||
|
||||
if _, err := os.Stat(path); !os.IsNotExist(err) {
|
||||
t.Fatalf("corrupt report file still exists after relaying: err = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelayUpdateReportWithNoFileIsSilent(t *testing.T) {
|
||||
b, sub := relayBoot(t)
|
||||
|
||||
b.relayUpdateReport(filepath.Join(t.TempDir(), "does-not-exist.json"))
|
||||
|
||||
if e, ok := waitForEventQuickly(sub); ok {
|
||||
t.Fatalf("published %+v with no report to relay", e)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStartUpdateRelayWithoutAPathDoesNothing: a deployment with no phase-2
|
||||
// reporting configured must not start a poller for a file that will never
|
||||
// exist.
|
||||
func TestStartUpdateRelayWithoutAPathDoesNothing(t *testing.T) {
|
||||
b, sub := relayBoot(t)
|
||||
|
||||
b.startUpdateRelay(t.Context(), "")
|
||||
|
||||
if e, ok := waitForEventQuickly(sub); ok {
|
||||
t.Fatalf("published %+v with no report path configured", e)
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
// TestBuildTreesAndIdentitiesBuildsRootManagerAndIdentityRunners pins the
|
||||
// daemon's tree composition, which the shared buildWorktreeManager must not
|
||||
// change: the daemon still owns the process-wide manager *and* one runner per
|
||||
// configured identity, each with its own WorkDir so concurrent identities
|
||||
// never clone into the same directory. The Gateway takes only the manager, so
|
||||
// this is the assertion that keeps the two roots apart.
|
||||
func TestBuildTreesAndIdentitiesBuildsRootManagerAndIdentityRunners(t *testing.T) {
|
||||
workDir := t.TempDir()
|
||||
cfg := config.Config{
|
||||
WorkDir: workDir,
|
||||
BotUser: "archie-bot",
|
||||
BotEmail: "bot@example.test",
|
||||
Forge: config.Forge{Host: "https://forge.example.test"},
|
||||
Identities: []config.IdentityConfig{{
|
||||
Name: "archie",
|
||||
BotUser: "archie-identity",
|
||||
}},
|
||||
}
|
||||
b := &boot{
|
||||
cfg: cfg,
|
||||
token: "daemon-forge-token",
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
secrets: secret.NewRegistry(),
|
||||
}
|
||||
|
||||
if err := b.buildTreesAndIdentities(t.Context()); err != nil {
|
||||
t.Fatalf("buildTreesAndIdentities = %v", err)
|
||||
}
|
||||
|
||||
if b.trees == nil {
|
||||
t.Fatal("b.trees = nil; the daemon would work no task")
|
||||
}
|
||||
if b.trees.WorkDir != workDir || b.trees.Token != b.token {
|
||||
t.Errorf("root worktree manager = {WorkDir:%q Token:%q}, want {%q %q}", b.trees.WorkDir, b.trees.Token, workDir, b.token)
|
||||
}
|
||||
if got := len(b.identityRunners); got != 1 {
|
||||
t.Fatalf("identityRunners = %d, want 1", got)
|
||||
}
|
||||
wantIdentityDir := filepath.Join(workDir, "identity-archie")
|
||||
if got := b.identityRunners[0].Trees.WorkDir; got != wantIdentityDir {
|
||||
t.Errorf("identity worktree manager WorkDir = %q, want %q", got, wantIdentityDir)
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// TestReloadChannelRefusesWhatCannotReload: the dashboard offers the action on the
|
||||
// strength of the capability its descriptor declares, so a channel that cannot
|
||||
// reload must be refused with a reason. Accepting and doing nothing is the failure
|
||||
// an operator cannot see through.
|
||||
func TestReloadChannelRefusesWhatCannotReload(t *testing.T) {
|
||||
srv, err := compose(t.Context(), deps{
|
||||
Config: ResolvedConfig{
|
||||
WebhookAddr: "127.0.0.1:0",
|
||||
Webhook: config.WebhookRoute{Path: "/smoke"},
|
||||
},
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Chat: &recordingChatContract{routes: make(chan messaging.Inbound, 1), reply: "ok"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("compose: %v", err)
|
||||
}
|
||||
|
||||
err = srv.ReloadChannel(t.Context(), "webhook")
|
||||
if err == nil {
|
||||
t.Fatal("ReloadChannel(webhook) = nil, want a refusal: webhook declares no reload support")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "does not support reload") {
|
||||
t.Errorf("error = %v, want it to say the channel does not support reload", err)
|
||||
}
|
||||
|
||||
if err := srv.ReloadChannel(t.Context(), "nope"); err == nil || !strings.Contains(err.Error(), "no channel") {
|
||||
t.Errorf("ReloadChannel(unknown) = %v, want it to name the missing channel", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReloadChannelReachesTheChannelsOwnSeam: the service routes a reload to the
|
||||
// channel's own implementation rather than reimplementing it, so the operator's
|
||||
// action and the front-end's own /restart path do the same thing.
|
||||
func TestReloadChannelReachesTheChannelsOwnSeam(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfgPath := filepath.Join(dir, "config.toml")
|
||||
write := func(userIDs string) {
|
||||
content := "bot_user = \"testbot\"\n\n[chat.telegram]\ntoken = { engine = \"env\", key = \"TEST_TG_TOKEN\" }\nallowed_user_ids = " + userIDs + "\n"
|
||||
if err := os.WriteFile(cfgPath, []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
write("[1]")
|
||||
t.Setenv("TEST_TG_TOKEN", "first-token")
|
||||
|
||||
resolved, err := Resolve(Options{Config: cfgPath}, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
srv, err := compose(t.Context(), deps{Config: resolved, Log: slog.New(slog.DiscardHandler), Chat: &recordingChatContract{}})
|
||||
if err != nil {
|
||||
t.Fatalf("compose: %v", err)
|
||||
}
|
||||
gateway := telegramChannel(t, srv)
|
||||
|
||||
write("[1, 2]")
|
||||
t.Setenv("TEST_TG_TOKEN", "second-token")
|
||||
if err := srv.ReloadChannel(t.Context(), "telegram"); err != nil {
|
||||
t.Fatalf("ReloadChannel(telegram): %v", err)
|
||||
}
|
||||
if len(gateway.AllowedUserIDs) != 2 || gateway.Token != "second-token" {
|
||||
t.Fatalf("after reload: allowlist %v, token %q; want the re-read config", gateway.AllowedUserIDs, gateway.Token)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReloadCapabilityAndActionShareOneSource pins the property that keeps the
|
||||
// dashboard honest: whatever a descriptor declares reloadable must be reloadable,
|
||||
// and vice versa, because both come from reloadable().
|
||||
func TestReloadCapabilityAndActionShareOneSource(t *testing.T) {
|
||||
srv, err := compose(t.Context(), deps{
|
||||
Config: ResolvedConfig{
|
||||
TelegramToken: "token-123",
|
||||
Telegram: config.TelegramConfig{Token: config.SecretRef{Engine: "env", Key: "TEST_TG_TOKEN"}, AllowedUserIDs: []int64{1}},
|
||||
WebhookAddr: "127.0.0.1:0",
|
||||
Webhook: config.WebhookRoute{Path: "/smoke"},
|
||||
},
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Chat: &recordingChatContract{routes: make(chan messaging.Inbound, 1), reply: "ok"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("compose: %v", err)
|
||||
}
|
||||
for _, report := range srv.ChannelStatus() {
|
||||
err := srv.ReloadChannel(t.Context(), report.ID)
|
||||
// A declared reload can still fail on the configuration it re-reads --
|
||||
// telegram refuses a config that lost its token, and the existing test for
|
||||
// that pins it. What the capability claims is that the ACTION exists and is
|
||||
// routed, so the property tested here is that the refusal is specifically
|
||||
// "does not support reload".
|
||||
unsupported := err != nil && strings.Contains(err.Error(), "does not support reload")
|
||||
if report.ReloadSupported == unsupported {
|
||||
t.Errorf("%s: ReloadSupported=%v but reload returned %v; the declaration and the action have drifted",
|
||||
report.ID, report.ReloadSupported, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// recordingChannelStatusStore records every report the service publishes.
|
||||
type recordingChannelStatusStore struct {
|
||||
mu sync.Mutex
|
||||
writes [][]storecontract.ChannelStatus
|
||||
}
|
||||
|
||||
func (s *recordingChannelStatusStore) PutChannelStatus(_ context.Context, channels []storecontract.ChannelStatus) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.writes = append(s.writes, append([]storecontract.ChannelStatus(nil), channels...))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *recordingChannelStatusStore) ChannelStatus(context.Context) ([]storecontract.ChannelStatus, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// waitForPublishedState polls the recorded reports until one carries the channel
|
||||
// in want, so the assertion races the publisher rather than the clock.
|
||||
func waitForPublishedState(t *testing.T, store *recordingChannelStatusStore, id, want string) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
store.mu.Lock()
|
||||
for _, write := range store.writes {
|
||||
for _, channel := range write {
|
||||
if channel.ID == id && channel.State == want {
|
||||
store.mu.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
store.mu.Unlock()
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
t.Fatalf("no report carried %s as %q; reports were %+v", id, want, store.writes)
|
||||
}
|
||||
|
||||
// TestServicePublishesChannelStatus is the point of archie-core-8cda.6.8: the
|
||||
// report has to reach the store the dashboard reads, not stay in this process.
|
||||
// Without this the surface exists and no operator ever sees it.
|
||||
func TestServicePublishesChannelStatus(t *testing.T) {
|
||||
writer := &recordingChannelStatusStore{}
|
||||
srv, err := compose(t.Context(), deps{
|
||||
ChannelStatus: writer,
|
||||
Config: ResolvedConfig{
|
||||
Options: Options{ShutdownTimeout: 2 * time.Second},
|
||||
WebhookAddr: fmt.Sprintf("127.0.0.1:%d", freePort(t)),
|
||||
Webhook: config.WebhookRoute{Path: "/smoke"},
|
||||
},
|
||||
Log: slog.Default(),
|
||||
Chat: &recordingChatContract{routes: make(chan messaging.Inbound, 1), reply: "ok"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("compose: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
started := make(chan error, 1)
|
||||
go func() { started <- srv.Start(ctx) }()
|
||||
|
||||
// The start-up report and the channel's own "starting" coalesce by design --
|
||||
// signals coalesce, because a reader only ever wants the latest state of every
|
||||
// channel -- so the first published state is either "configured" or "starting"
|
||||
// depending on which side wins. What must hold is that the transitions reach
|
||||
// the store, and that the last word is the truth.
|
||||
waitForPublishedState(t, writer, "webhook", "running")
|
||||
|
||||
srv.Stop()
|
||||
select {
|
||||
case err := <-started:
|
||||
if err != nil {
|
||||
t.Fatalf("srv.Start returned %v, want a clean stop", err)
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("srv.Start did not return after Stop")
|
||||
}
|
||||
// The final report is what leaves the store honest about a stopped service.
|
||||
waitForPublishedState(t, writer, "webhook", "stopped")
|
||||
}
|
||||
@@ -1,184 +0,0 @@
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels"
|
||||
"github.com/samcharles93/archie-core/internal/channels/status"
|
||||
"github.com/samcharles93/archie-core/internal/channels/telegram"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// waitForState polls the service's own report until the channel reaches want, so
|
||||
// the assertion races the channel's goroutine rather than the clock.
|
||||
func waitForState(t *testing.T, srv *Service, id string, want status.State) status.Status {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
var last status.Status
|
||||
for time.Now().Before(deadline) {
|
||||
for _, candidate := range srv.ChannelStatus() {
|
||||
if candidate.ID != id {
|
||||
continue
|
||||
}
|
||||
last = candidate
|
||||
if candidate.State == want {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("channel %s never reached %s; last report %+v", id, want, last)
|
||||
return status.Status{}
|
||||
}
|
||||
|
||||
// TestServiceRecordsChannelLifecycle pins the fact archie-core-8cda.6.8 is about:
|
||||
// a channel's own report reaches a manager. Before this the service handed every
|
||||
// channel an empty Lifecycle, so starting/running/stopped were recorded nowhere
|
||||
// and internal/channels/status.Manager had no production writer at all.
|
||||
func TestServiceRecordsChannelLifecycle(t *testing.T) {
|
||||
port := freePort(t)
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", port)
|
||||
|
||||
srv, err := compose(t.Context(), deps{
|
||||
Config: ResolvedConfig{
|
||||
Options: Options{ShutdownTimeout: 2 * time.Second},
|
||||
WebhookAddr: addr,
|
||||
Webhook: config.WebhookRoute{Path: "/smoke"},
|
||||
},
|
||||
Log: slog.Default(),
|
||||
Chat: &recordingChatContract{routes: make(chan messaging.Inbound, 1), reply: "ok"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("compose: %v", err)
|
||||
}
|
||||
|
||||
// Composed but not started: the only honest thing to report is configured.
|
||||
composed := srv.ChannelStatus()
|
||||
if len(composed) != 1 || composed[0].State != status.StateConfigured {
|
||||
t.Fatalf("ChannelStatus before Start = %+v, want one configured channel", composed)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
started := make(chan error, 1)
|
||||
go func() { started <- srv.Start(ctx) }()
|
||||
|
||||
running := waitForState(t, srv, "webhook", status.StateRunning)
|
||||
|
||||
srv.Stop()
|
||||
select {
|
||||
case err := <-started:
|
||||
if err != nil {
|
||||
t.Fatalf("srv.Start returned %v, want a clean stop", err)
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("srv.Start did not return after Stop")
|
||||
}
|
||||
stopped := waitForState(t, srv, "webhook", status.StateStopped)
|
||||
if stopped.State != status.StateStopped {
|
||||
t.Fatalf("state after Stop = %s, want stopped", stopped.State)
|
||||
}
|
||||
|
||||
// The descriptor is the operator-facing half, and it must not carry
|
||||
// configuration: a token in here would make the manager a second source for a
|
||||
// credential.
|
||||
if !running.Configured || running.Name != "webhook" {
|
||||
t.Errorf("status = %+v, want a configured, named webhook", running)
|
||||
}
|
||||
if running.ReloadSupported {
|
||||
t.Error("webhook declares reload support, but no reload seam backs it")
|
||||
}
|
||||
}
|
||||
|
||||
// TestServiceRecordsAChannelThatCannotStart is the half a status surface exists
|
||||
// for: a channel that died must be visible on the operator's surface, not only in
|
||||
// the log, because "nothing reported" and "nothing running" look identical on a
|
||||
// dashboard.
|
||||
func TestServiceRecordsAChannelThatCannotStart(t *testing.T) {
|
||||
// Hold the port, so the channel's own listen fails deterministically.
|
||||
var lc net.ListenConfig
|
||||
occupied, err := lc.Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("occupy a port: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = occupied.Close() })
|
||||
|
||||
srv, err := compose(t.Context(), deps{
|
||||
Config: ResolvedConfig{
|
||||
Options: Options{ShutdownTimeout: 2 * time.Second},
|
||||
WebhookAddr: occupied.Addr().String(),
|
||||
Webhook: config.WebhookRoute{Path: "/smoke"},
|
||||
},
|
||||
Log: slog.Default(),
|
||||
Chat: &recordingChatContract{routes: make(chan messaging.Inbound, 1), reply: "ok"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("compose: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
started := make(chan error, 1)
|
||||
go func() { started <- srv.Start(ctx) }()
|
||||
t.Cleanup(srv.Stop)
|
||||
|
||||
failed := waitForState(t, srv, "webhook", status.StateFailed)
|
||||
if failed.Detail == "" {
|
||||
t.Error("a failed channel carries no detail; the operator cannot tell why it is down")
|
||||
}
|
||||
}
|
||||
|
||||
// TestChannelDescriptorsDeclareCapabilities pins the declarations the dashboard
|
||||
// acts on. Reload is the one with a real consequence: a channel declaring it
|
||||
// invites a button that must do something.
|
||||
func TestChannelDescriptorsDeclareCapabilities(t *testing.T) {
|
||||
// Telegram is a real gateway with a reload seam: the capability now derives
|
||||
// from the channel and its seam, not from its name, so a fakeChannel named
|
||||
// "telegram" correctly declares nothing.
|
||||
withReload := telegram.New("token-123", []int64{1}, slog.New(slog.DiscardHandler))
|
||||
withReload.Reload = func(*telegram.Gateway) error { return nil }
|
||||
descriptors := channelDescriptors([]*channelInstance{
|
||||
{name: "telegram", channel: withReload},
|
||||
{name: "email", channel: fakeChannel{}},
|
||||
{name: "webhook", channel: fakeChannel{}},
|
||||
})
|
||||
if len(descriptors) != 3 {
|
||||
t.Fatalf("descriptors = %+v, want one per composed channel", descriptors)
|
||||
}
|
||||
byID := map[string]status.Descriptor{}
|
||||
for _, descriptor := range descriptors {
|
||||
byID[descriptor.ID] = descriptor
|
||||
}
|
||||
if !byID["telegram"].ReloadSupported {
|
||||
t.Error("telegram does not declare reload support, but it is the channel with a reload seam")
|
||||
}
|
||||
for _, id := range []string{"email", "webhook"} {
|
||||
if byID[id].ReloadSupported {
|
||||
t.Errorf("%s declares reload support with nothing backing it", id)
|
||||
}
|
||||
}
|
||||
for id, descriptor := range byID {
|
||||
if !descriptor.Configured {
|
||||
t.Errorf("%s is composed but not declared configured", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fakeChannel satisfies channels.Channel for descriptor tests, which read identity
|
||||
// and capabilities only.
|
||||
type fakeChannel struct{}
|
||||
|
||||
func (fakeChannel) Name() string { return "fake" }
|
||||
func (fakeChannel) Stop(context.Context) error { return nil }
|
||||
func (fakeChannel) ConfigSchema() json.RawMessage { return json.RawMessage(`{}`) }
|
||||
func (fakeChannel) ValidateConfig(map[string]any) error { return nil }
|
||||
func (fakeChannel) Start(context.Context, messaging.ChatContract, channels.Lifecycle) error {
|
||||
return nil
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestOptionsDefaultsAndValidation(t *testing.T) {
|
||||
opts := withDefaults(Options{})
|
||||
if opts.Gateway.Target != defaultGatewayTarget {
|
||||
t.Errorf("Gateway.Target = %q, want %q", opts.Gateway.Target, defaultGatewayTarget)
|
||||
}
|
||||
if opts.DependencyTimeout != defaultDependencyTimeout {
|
||||
t.Errorf("DependencyTimeout = %v, want %v", opts.DependencyTimeout, defaultDependencyTimeout)
|
||||
}
|
||||
if err := opts.validate(); err != nil {
|
||||
t.Errorf("validate default loopback options: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOptionsNonLoopbackRequiresToken(t *testing.T) {
|
||||
opts := Options{
|
||||
Gateway: ServiceTarget{Target: "192.168.1.50:8585"},
|
||||
}
|
||||
opts = withDefaults(opts)
|
||||
if err := opts.validate(); err == nil {
|
||||
t.Error("validate non-loopback gateway target with empty token want error, got nil")
|
||||
}
|
||||
|
||||
opts.Gateway.Token = "secret"
|
||||
if err := opts.validate(); err != nil {
|
||||
t.Errorf("validate non-loopback gateway target with token: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveWithConfigFile(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
cfgPath := filepath.Join(tmp, "config.toml")
|
||||
content := `
|
||||
bot_user = "testbot"
|
||||
|
||||
[services.gateway]
|
||||
target = "127.0.0.1:8999"
|
||||
target_token = "tok-123"
|
||||
|
||||
[chat.telegram]
|
||||
token = { engine = "env", key = "TEST_TG_TOKEN" }
|
||||
allowed_user_ids = [12345]
|
||||
`
|
||||
if err := os.WriteFile(cfgPath, []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("TEST_TG_TOKEN", "resolved-tg-token")
|
||||
|
||||
resolved, err := Resolve(Options{Config: cfgPath}, slog.Default())
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
|
||||
if resolved.Options.Gateway.Target != "127.0.0.1:8999" {
|
||||
t.Errorf("Gateway.Target = %q, want 127.0.0.1:8999", resolved.Options.Gateway.Target)
|
||||
}
|
||||
if resolved.TelegramToken != "resolved-tg-token" {
|
||||
t.Errorf("TelegramToken = %q, want resolved-tg-token", resolved.TelegramToken)
|
||||
}
|
||||
if len(resolved.Telegram.AllowedUserIDs) != 1 || resolved.Telegram.AllowedUserIDs[0] != 12345 {
|
||||
t.Errorf("AllowedUserIDs = %v, want [12345]", resolved.Telegram.AllowedUserIDs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceStartAndStop(t *testing.T) {
|
||||
d := deps{
|
||||
Config: ResolvedConfig{
|
||||
Options: withDefaults(Options{}),
|
||||
},
|
||||
Log: slog.Default(),
|
||||
}
|
||||
srv, err := compose(t.Context(), d)
|
||||
if err != nil {
|
||||
t.Fatalf("compose: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := contextWithTimeout(t, 200*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- srv.Start(ctx)
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
if err != nil {
|
||||
t.Fatalf("srv.Start: %v", err)
|
||||
}
|
||||
case <-time.After(1 * time.Second):
|
||||
t.Fatal("srv.Start timed out waiting for context cancel")
|
||||
}
|
||||
|
||||
srv.Stop()
|
||||
}
|
||||
|
||||
func contextWithTimeout(t *testing.T, d time.Duration) (context.Context, context.CancelFunc) {
|
||||
t.Helper()
|
||||
return context.WithTimeout(context.Background(), d)
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/sdnotify"
|
||||
)
|
||||
|
||||
// notifyListener is a stand-in for systemd's NOTIFY_SOCKET: a unixgram socket
|
||||
// that collects the state lines the service sends. It is bound to the real
|
||||
// NOTIFY_SOCKET for the duration of the test.
|
||||
type notifyListener struct {
|
||||
conn *net.UnixConn
|
||||
}
|
||||
|
||||
// listenNotify binds a notify socket in the test's temp dir and points
|
||||
// NOTIFY_SOCKET at it. A unix socket path is capped near 108 bytes, so the
|
||||
// short file name is what keeps the path inside t.TempDir() under that.
|
||||
func listenNotify(t *testing.T) *notifyListener {
|
||||
t.Helper()
|
||||
addr := filepath.Join(t.TempDir(), "n.sock")
|
||||
conn, err := net.ListenUnixgram("unixgram", &net.UnixAddr{Name: addr, Net: "unixgram"})
|
||||
if err != nil {
|
||||
t.Fatalf("listen for notify datagrams at %q: %v", addr, err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
t.Setenv(sdnotify.NotifySocketEnv, addr)
|
||||
return ¬ifyListener{conn: conn}
|
||||
}
|
||||
|
||||
// waitForState reads datagrams until one carries want or the window closes.
|
||||
func (l *notifyListener) waitForState(t *testing.T, window time.Duration, want string) bool {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(window)
|
||||
buf := make([]byte, 1024)
|
||||
for time.Now().Before(deadline) {
|
||||
if err := l.conn.SetReadDeadline(time.Now().Add(50 * time.Millisecond)); err != nil {
|
||||
t.Fatalf("set notify read deadline: %v", err)
|
||||
}
|
||||
n, _, err := l.conn.ReadFromUnix(buf)
|
||||
if err != nil {
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) && netErr.Timeout() {
|
||||
continue
|
||||
}
|
||||
t.Fatalf("read notify datagram: %v", err)
|
||||
}
|
||||
if string(buf[:n]) == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// TestServiceAnnouncesReadyWhenServing: archie-messaging run as a Type=notify
|
||||
// unit must send READY=1 at the moment it declares itself serving, or systemd
|
||||
// kills a healthy process once TimeoutStartSec expires. It could not before:
|
||||
// the client lived in internal/app/archied, which this process cannot import
|
||||
// (archie-core-g5g8). The announcement is judged against the same evidence the
|
||||
// other serve paths use -- the process itself says it is serving -- and not
|
||||
// against a second notion of started invented here.
|
||||
func TestServiceAnnouncesReadyWhenServing(t *testing.T) {
|
||||
listener := listenNotify(t)
|
||||
|
||||
srv, err := compose(t.Context(), deps{
|
||||
Config: ResolvedConfig{Options: Options{ShutdownTimeout: 2 * time.Second}},
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Chat: &dummyChatContract{},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("compose: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
started := make(chan error, 1)
|
||||
go func() { started <- srv.Start(ctx) }()
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
srv.Stop()
|
||||
select {
|
||||
case err := <-started:
|
||||
if err != nil {
|
||||
t.Errorf("srv.Start returned %v, want a clean stop", err)
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Error("srv.Start did not return after Stop, so a channel leaked its goroutine")
|
||||
}
|
||||
})
|
||||
|
||||
if !listener.waitForState(t, 5*time.Second, sdnotify.ReadyState) {
|
||||
t.Fatal("no READY=1 datagram within 5s of the Messaging Service serving")
|
||||
}
|
||||
}
|
||||
@@ -1,253 +0,0 @@
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels/status"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/applystatus"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// channelByID returns the live instance the service currently serves for id.
|
||||
func channelByID(t *testing.T, srv *Service, id string) *channelInstance {
|
||||
t.Helper()
|
||||
for _, instance := range srv.channels {
|
||||
if instance.name == id {
|
||||
return instance
|
||||
}
|
||||
}
|
||||
t.Fatalf("no channel %q composed", id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// channelAddrs reserves two loopback ports, one per channel.
|
||||
func channelAddrs(t *testing.T) (emailAddr, webhookAddr string) {
|
||||
t.Helper()
|
||||
return fmt.Sprintf("127.0.0.1:%d", freePort(t)), fmt.Sprintf("127.0.0.1:%d", freePort(t))
|
||||
}
|
||||
|
||||
// writeChannelConfig writes a file document with email and webhook enabled. A
|
||||
// file rather than a hand-built ResolvedConfig, because the reconcile path
|
||||
// re-resolves the file exactly as production does; a hand-built config would
|
||||
// prove nothing about that half.
|
||||
func writeChannelConfig(t *testing.T, emailAddr, webhookAddr, route string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
content := fmt.Sprintf("bot_user = \"testbot\"\n\n[chat]\nwebhook_addr = %q\n\n[chat.email]\nlisten_addr = %q\n\n[chat.webhook]\npath = %q\n",
|
||||
webhookAddr, emailAddr, route)
|
||||
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func resolveChannels(t *testing.T, emailAddr, webhookAddr, route string) ResolvedConfig {
|
||||
t.Helper()
|
||||
cfg, err := Resolve(
|
||||
Options{Config: writeChannelConfig(t, emailAddr, webhookAddr, route), ShutdownTimeout: 2 * time.Second},
|
||||
slog.New(slog.DiscardHandler),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
// startComposed starts a composed service and waits for its channels to run.
|
||||
func startComposed(t *testing.T, d deps) *Service {
|
||||
t.Helper()
|
||||
srv, err := compose(t.Context(), d)
|
||||
if err != nil {
|
||||
t.Fatalf("compose: %v", err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
started := make(chan error, 1)
|
||||
go func() { started <- srv.Start(ctx) }()
|
||||
t.Cleanup(func() {
|
||||
srv.Stop()
|
||||
cancel()
|
||||
select {
|
||||
case err := <-started:
|
||||
if err != nil {
|
||||
t.Errorf("srv.Start returned %v, want a clean stop", err)
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Error("srv.Start did not return after Stop")
|
||||
}
|
||||
})
|
||||
waitForState(t, srv, "email", status.StateRunning)
|
||||
waitForState(t, srv, "webhook", status.StateRunning)
|
||||
return srv
|
||||
}
|
||||
|
||||
// startChannels composes and starts email and webhook. Those two are the
|
||||
// channels a test can run without an external service, and a restart of one is
|
||||
// observable as the channel pointer changing.
|
||||
func startChannels(t *testing.T) *Service {
|
||||
t.Helper()
|
||||
emailAddr, webhookAddr := channelAddrs(t)
|
||||
return startComposed(t, deps{
|
||||
Config: resolveChannels(t, emailAddr, webhookAddr, "/a"),
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Chat: &recordingChatContract{routes: make(chan messaging.Inbound, 1), reply: "ok"},
|
||||
})
|
||||
}
|
||||
|
||||
// TestApplyChannelSettingsRestartsOnlyTheChangedChannel is the bead's core
|
||||
// property: a change to one channel restarts that channel and leaves the others
|
||||
// serving. Before the per-channel supervisor this could only be a process
|
||||
// restart, which restarted every channel (archie-core-zfb0.4).
|
||||
func TestApplyChannelSettingsRestartsOnlyTheChangedChannel(t *testing.T) {
|
||||
srv := startChannels(t)
|
||||
webhookBefore := channelByID(t, srv, "webhook").current()
|
||||
emailBefore := channelByID(t, srv, "email").current()
|
||||
|
||||
next := srv.currentConfig()
|
||||
next.Webhook = config.WebhookRoute{Path: "/b"}
|
||||
if _, err := srv.applyChannelSettings(next); err != nil {
|
||||
t.Fatalf("applyChannelSettings: %v", err)
|
||||
}
|
||||
|
||||
if got := channelByID(t, srv, "webhook").current(); got == webhookBefore {
|
||||
t.Error("webhook did not restart after its route changed")
|
||||
}
|
||||
if got := channelByID(t, srv, "email").current(); got != emailBefore {
|
||||
t.Error("email restarted when only the webhook route changed")
|
||||
}
|
||||
}
|
||||
|
||||
// TestApplyChannelSettingsRefusesAListenAddressChange is the path where the
|
||||
// change must NOT apply: a bound listen address is a process binding, and
|
||||
// rebinding it in place is exactly the restart the epic keeps. The running
|
||||
// channel is left alone and the change is reported instead.
|
||||
func TestApplyChannelSettingsRefusesAListenAddressChange(t *testing.T) {
|
||||
srv := startChannels(t)
|
||||
before := channelByID(t, srv, "webhook").current()
|
||||
|
||||
next := srv.currentConfig()
|
||||
next.WebhookAddr = fmt.Sprintf("127.0.0.1:%d", freePort(t))
|
||||
_, err := srv.applyChannelSettings(next)
|
||||
if err == nil {
|
||||
t.Fatal("applyChannelSettings error = nil, want the listen-address change reported")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "webhook_addr") {
|
||||
t.Errorf("error = %v, want it to name chat.webhook_addr", err)
|
||||
}
|
||||
if got := channelByID(t, srv, "webhook").current(); got != before {
|
||||
t.Error("webhook restarted for a listen-address change; a bound address must not move in place")
|
||||
}
|
||||
}
|
||||
|
||||
// TestApplyChannelSettingsRestartsNothingWhenNothingChanged: the other half of
|
||||
// "only the channels whose settings changed" -- a tick that carries no change
|
||||
// must not restart a healthy channel.
|
||||
func TestApplyChannelSettingsRestartsNothingWhenNothingChanged(t *testing.T) {
|
||||
srv := startChannels(t)
|
||||
webhookBefore := channelByID(t, srv, "webhook").current()
|
||||
emailBefore := channelByID(t, srv, "email").current()
|
||||
|
||||
if _, err := srv.applyChannelSettings(srv.currentConfig()); err != nil {
|
||||
t.Fatalf("applyChannelSettings: %v", err)
|
||||
}
|
||||
if channelByID(t, srv, "webhook").current() != webhookBefore {
|
||||
t.Error("webhook restarted with no settings change")
|
||||
}
|
||||
if channelByID(t, srv, "email").current() != emailBefore {
|
||||
t.Error("email restarted with no settings change")
|
||||
}
|
||||
}
|
||||
|
||||
// fakeChannelSettings is the stored channel-settings resource a test owns. It
|
||||
// returns the document a real store would: the file's values with the stored
|
||||
// route layered over them, so the reconcile's layering is exercised rather than
|
||||
// bypassed.
|
||||
type fakeChannelSettings struct {
|
||||
mu sync.Mutex
|
||||
settings config.ChatConfig
|
||||
version int64
|
||||
}
|
||||
|
||||
func (f *fakeChannelSettings) RuntimeChatConfig(_ context.Context, base config.ChatConfig) (config.ChatConfig, int64, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
out := base
|
||||
out.Webhook = f.settings.Webhook
|
||||
return out, f.version, nil
|
||||
}
|
||||
|
||||
func (f *fakeChannelSettings) set(version int64, route config.WebhookRoute) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.version, f.settings.Webhook = version, route
|
||||
}
|
||||
|
||||
// recordingApplyStore records the apply-status writes the service makes.
|
||||
type recordingApplyStore struct {
|
||||
mu sync.Mutex
|
||||
writes []storecontract.ApplyStatus
|
||||
}
|
||||
|
||||
func (s *recordingApplyStore) PutApplyStatus(_ context.Context, st storecontract.ApplyStatus) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.writes = append(s.writes, st)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *recordingApplyStore) ListApplyStatus(context.Context) ([]storecontract.ApplyStatus, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *recordingApplyStore) appliedVersion() int64 {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
var version int64
|
||||
for _, st := range s.writes {
|
||||
version = max(version, st.AppliedVersion)
|
||||
}
|
||||
return version
|
||||
}
|
||||
|
||||
// TestReconcileAppliesANewStoredVersion drives the whole live path: the service
|
||||
// reads the stored channel settings on its interval, sees a newer version, and
|
||||
// restarts the channel it changed. The applied version reaches apply status, so
|
||||
// the dashboard stops showing the change as pending.
|
||||
func TestReconcileAppliesANewStoredVersion(t *testing.T) {
|
||||
emailAddr, webhookAddr := channelAddrs(t)
|
||||
source := &fakeChannelSettings{}
|
||||
source.set(1, config.WebhookRoute{Path: "/a"})
|
||||
store := &recordingApplyStore{}
|
||||
|
||||
srv := startComposed(t, deps{
|
||||
Config: resolveChannels(t, emailAddr, webhookAddr, "/a"),
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Chat: &recordingChatContract{routes: make(chan messaging.Inbound, 1), reply: "ok"},
|
||||
SettingsSource: source,
|
||||
ApplyReporter: applystatus.New(applystatus.Messaging, store, slog.New(slog.DiscardHandler)),
|
||||
AppliedVersion: 1,
|
||||
ReconcileInterval: 5 * time.Millisecond,
|
||||
})
|
||||
|
||||
before := channelByID(t, srv, "webhook").current()
|
||||
source.set(2, config.WebhookRoute{Path: "/b"})
|
||||
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if channelByID(t, srv, "webhook").current() != before && store.appliedVersion() >= 2 {
|
||||
return
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("after the stored version moved to 2: channel replaced=%v, applied version=%d; want both",
|
||||
channelByID(t, srv, "webhook").current() != before, store.appliedVersion())
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
type dummyChatContract struct {
|
||||
messaging.ChatContract
|
||||
}
|
||||
|
||||
func TestServiceStartsConfiguredChannels(t *testing.T) {
|
||||
d := deps{
|
||||
Config: ResolvedConfig{
|
||||
TelegramToken: "token-123",
|
||||
Telegram: config.TelegramConfig{
|
||||
Token: config.SecretRef{Engine: "env", Key: "TEST_TG_TOKEN"},
|
||||
AllowedUserIDs: []int64{123},
|
||||
},
|
||||
Email: config.EmailConfig{
|
||||
ListenAddr: "127.0.0.1:0",
|
||||
},
|
||||
WebhookAddr: "127.0.0.1:0",
|
||||
},
|
||||
Log: slog.Default(),
|
||||
Chat: &dummyChatContract{},
|
||||
}
|
||||
|
||||
srv, err := compose(t.Context(), d)
|
||||
if err != nil {
|
||||
t.Fatalf("compose: %v", err)
|
||||
}
|
||||
if len(srv.channels) != 3 {
|
||||
t.Fatalf("len(srv.channels) = %d, want 3", len(srv.channels))
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- srv.Start(ctx)
|
||||
}()
|
||||
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
srv.Stop()
|
||||
|
||||
select {
|
||||
case startErr := <-errCh:
|
||||
if startErr != nil {
|
||||
t.Fatalf("srv.Start error: %v", startErr)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("srv.Start did not exit after Stop")
|
||||
}
|
||||
}
|
||||
|
||||
// TestComposeRejectsInvalidChannelConfig pins that a configured front-end
|
||||
// whose own ValidateConfig refuses the config fails composition. Dropping it
|
||||
// instead would leave the operator with a service that starts cleanly and
|
||||
// answers nothing on that channel.
|
||||
func TestComposeRejectsInvalidChannelConfig(t *testing.T) {
|
||||
_, err := compose(t.Context(), deps{
|
||||
Config: ResolvedConfig{
|
||||
Email: config.EmailConfig{ListenAddr: "127.0.0.1:0"},
|
||||
},
|
||||
Log: slog.Default(),
|
||||
Chat: &dummyChatContract{},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("compose with a valid email listen addr: %v", err)
|
||||
}
|
||||
|
||||
_, err = compose(t.Context(), deps{
|
||||
Config: ResolvedConfig{
|
||||
TelegramToken: "token-123",
|
||||
// No token ref: telegram.ValidateConfig refuses.
|
||||
},
|
||||
Log: slog.Default(),
|
||||
Chat: &dummyChatContract{},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("compose error = nil, want an error: telegram has no configured credential source")
|
||||
}
|
||||
}
|
||||
@@ -1,188 +0,0 @@
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// recordingChatContract records the turn the Messaging Service dispatched and
|
||||
// answers it, so a round trip can be asserted on what actually crossed the
|
||||
// service boundary rather than on what a channel meant to send.
|
||||
type recordingChatContract struct {
|
||||
messaging.ChatContract
|
||||
routes chan messaging.Inbound
|
||||
reply string
|
||||
}
|
||||
|
||||
func (c *recordingChatContract) Route(_ context.Context, in messaging.Inbound) (messaging.ChatReply, error) {
|
||||
c.routes <- in
|
||||
return messaging.ChatReply{Text: c.reply, SessionID: "smoke-session"}, nil
|
||||
}
|
||||
|
||||
// freePort reserves a loopback port and releases it, so the composed service can
|
||||
// be given a concrete address. A webhook bound to port 0 composes fine, but
|
||||
// nothing exposes the port the listener actually received, and a round trip needs
|
||||
// somewhere to send the request.
|
||||
func freePort(t *testing.T) int {
|
||||
t.Helper()
|
||||
var lc net.ListenConfig
|
||||
listener, err := lc.Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("reserve a loopback port: %v", err)
|
||||
}
|
||||
defer func() { _ = listener.Close() }()
|
||||
bound, ok := listener.Addr().(*net.TCPAddr)
|
||||
if !ok {
|
||||
t.Fatalf("listener address %T is not a TCP address", listener.Addr())
|
||||
}
|
||||
return bound.Port
|
||||
}
|
||||
|
||||
// waitForListener polls until something accepts on addr, so the request below
|
||||
// races the channel's own goroutine rather than the clock.
|
||||
func waitForListener(t *testing.T, addr string) {
|
||||
t.Helper()
|
||||
dialer := net.Dialer{Timeout: 200 * time.Millisecond}
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
conn, err := dialer.DialContext(t.Context(), "tcp", addr)
|
||||
if err == nil {
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("nothing accepted on %s within the deadline", addr)
|
||||
}
|
||||
|
||||
func sign(t *testing.T, secret string, body []byte) string {
|
||||
t.Helper()
|
||||
mac := hmac.New(sha256.New, []byte(secret))
|
||||
mac.Write(body)
|
||||
return "sha256=" + hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// TestWebhookChannelSmokeRoundTrip is archie-core-8cda.6.5's end-to-end smoke
|
||||
// verification: the real composition, the real webhook adapter, a real listener,
|
||||
// and a real signed HTTP request -- asserted on the inbound the service hands its
|
||||
// chat contract and on the reply the caller receives back.
|
||||
//
|
||||
// Webhook is the channel this can be done for without external services. Telegram
|
||||
// needs a bot token and the Telegram API and email needs SMTP; neither is
|
||||
// something a test can own. docs/prds/messaging-service-boundary.md's fourth
|
||||
// criterion asks for a live Telegram round trip "or equivalent channel smoke
|
||||
// test", and this is that equivalent -- every step between the POST and the
|
||||
// contract is the deployed code path. The gRPC hop beyond the contract is covered
|
||||
// by internal/infrastructure/gatewayrpc's conformance tests, which exercise the
|
||||
// same client and server in both local and remote mode.
|
||||
func TestWebhookChannelSmokeRoundTrip(t *testing.T) {
|
||||
port := freePort(t)
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", port)
|
||||
const (
|
||||
routePath = "/smoke"
|
||||
secret = "smoke-secret"
|
||||
reply = "ack from the contract"
|
||||
)
|
||||
body := []byte(`{"issue":{"title":"a smoke-test issue"}}`)
|
||||
|
||||
contract := &recordingChatContract{routes: make(chan messaging.Inbound, 1), reply: reply}
|
||||
srv, err := compose(t.Context(), deps{
|
||||
Config: ResolvedConfig{
|
||||
Options: Options{ShutdownTimeout: 2 * time.Second},
|
||||
WebhookAddr: addr,
|
||||
Webhook: config.WebhookRoute{Path: routePath, Template: "issue.title", DeliverTo: "origin"},
|
||||
WebhookSecret: secret,
|
||||
},
|
||||
Log: slog.Default(),
|
||||
Chat: contract,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("compose: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
started := make(chan error, 1)
|
||||
go func() { started <- srv.Start(ctx) }()
|
||||
t.Cleanup(func() {
|
||||
srv.Stop()
|
||||
select {
|
||||
case err := <-started:
|
||||
if err != nil {
|
||||
t.Errorf("srv.Start returned %v, want a clean stop", err)
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Error("srv.Start did not return after Stop, so a channel leaked its goroutine")
|
||||
}
|
||||
})
|
||||
|
||||
waitForListener(t, addr)
|
||||
|
||||
request, err := http.NewRequestWithContext(t.Context(), http.MethodPost,
|
||||
"http://"+addr+routePath, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatalf("build request: %v", err)
|
||||
}
|
||||
request.Header.Set("X-Hub-Signature-256", sign(t, secret, body))
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("post to the webhook channel: %v", err)
|
||||
}
|
||||
defer func() { _ = response.Body.Close() }()
|
||||
got, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read response: %v", err)
|
||||
}
|
||||
|
||||
// The reply travelled back: DeliverTo=origin means the contract's answer is the
|
||||
// HTTP response body, so this asserts the whole path rather than half of it.
|
||||
if response.StatusCode != http.StatusOK {
|
||||
t.Errorf("status = %d, want 200 (body %q)", response.StatusCode, got)
|
||||
}
|
||||
if strings.TrimSpace(string(got)) != reply {
|
||||
t.Errorf("response body = %q, want the contract's reply %q", got, reply)
|
||||
}
|
||||
|
||||
select {
|
||||
case in := <-contract.routes:
|
||||
if in.Message.Text != "a smoke-test issue" {
|
||||
t.Errorf("Text = %q, want the templated title", in.Message.Text)
|
||||
}
|
||||
if in.Message.Role != messaging.RoleUser {
|
||||
t.Errorf("Role = %q, want the channel's messages to arrive as a user's", in.Message.Role)
|
||||
}
|
||||
if in.Message.ConversationID.ChannelID != routePath {
|
||||
t.Errorf("ChannelID = %q, want the configured route path %q", in.Message.ConversationID.ChannelID, routePath)
|
||||
}
|
||||
// The three transport facts this channel must carry, each of which has a
|
||||
// reason recorded elsewhere: the platform is how the Gateway learns which
|
||||
// channel it serves (archie-core-c1qx); SenderID stays empty because a route
|
||||
// path is a source and not a person (archie-core-oyna); and the route
|
||||
// survives as the budget key so the inbound limit still applies.
|
||||
if in.Platform != "webhook" {
|
||||
t.Errorf("Platform = %q, want %q", in.Platform, "webhook")
|
||||
}
|
||||
if in.Message.SenderID != "" {
|
||||
t.Errorf("SenderID = %q, want empty: a route path must never become a user identity", in.Message.SenderID)
|
||||
}
|
||||
if in.BudgetKey != routePath {
|
||||
t.Errorf("BudgetKey = %q, want the route path %q", in.BudgetKey, routePath)
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("the webhook channel never reached the chat contract")
|
||||
}
|
||||
}
|
||||
Loaded 100 of 651 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user