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,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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user