Files
archie/internal/agentexec/nats_test.go
T
sam 9d5040fd65 refactor: add internal/eventbus as the broker-neutral messaging contract
dependencies-and-contracts.md rule 1 says domains must not import
internal/infrastructure. internal/daemon and internal/agentexec both did,
and for exactly the thing the doc carves out: "internal/eventbus is an
approved shared application contract ... it MUST remain broker-neutral."

The Publisher/Consumer/Requester interfaces existed but lived inside the
NATS package, so a caller could depend on the behaviour yet still had to
import the implementation to name it. They now live in internal/eventbus,
and nats.Client asserts against eventbus.Bus.

The larger violation was ownership of meaning. The doc says "message schemas
stay with their owning domains; the event bus transports messages, it does
not own their meaning." The bus exported TaskEnvelope and a PublishTask
method, so the transport knew what a unit of work was, and it exported the
archie.agent.* subject helpers, so it also owned the agent protocol.

  - TaskEnvelope, its routing Kind, the label vocabulary and the task
    subjects move to internal/domain/workintake, which encodes and decodes
    its own bytes. This starts internal/domain/ per organisation.md.
  - The agent request/response/system subjects move to internal/agentexec,
    which defines what those messages mean.
  - internal/workflow keeps only the kind-to-registry mapping; the label
    table stays single and lives with the domain that reads forge issues.
  - The bus now carries opaque payloads on plain-string subjects.

Consumers declare the smallest interface they need rather than taking the
whole Bus: daemon.TaskBus is publish-unique/fetch/request, agentexec.
RequestBus is publish-request/reply-inbox, and archie-agent's stageBus is
fetch/respond. None can reach what it does not use.

Two defects this surfaced:

  - archie-agent declared its own JetStream stream with a second copy of the
    name, subjects, retention, dedup window, MaxDeliver and TTLs that
    nats.Connect already sets -- two definitions of one stream, free to
    diverge. Config now takes Subjects and FilterSubject from composition,
    which is what let the agent use the shared client and delete its
    hand-rolled setup.
  - Replying to a request needs core NATS, not the JetStream publish path:
    a reply inbox is ephemeral and belongs to no stream, so a durable
    publish to it fails. The old code hid this by using the raw connection.
    The contract now distinguishes Respond from Publish. The agentexec
    round-trip test caught it after I had made the same mistake in
    archie-agent.

Also translated the SDK's ErrNoResponders into eventbus.ErrNoResponders, so
the daemon's taskrun retry no longer imports the NATS SDK to name a
transient condition. The SDK is now confined to the nats package, the *rpc
packages (themselves NATS infrastructure), and cmd/*.

The agentexec test fake previously hand-rolled a JetStream consumer; it now
drains the client's own consumer, which is both closer to production and
avoids conflicting consumers on a work-queue stream.

Verified: go build, go vet, gofmt clean; full test suite passes.
2026-07-29 11:40:24 +10:00

286 lines
9.0 KiB
Go

package agentexec
import (
"context"
"encoding/json"
"log/slog"
"testing"
"github.com/nats-io/nats-server/v2/server"
natssrv "github.com/nats-io/nats-server/v2/test"
"github.com/samcharles93/archie-core/internal/domain/workintake"
"github.com/samcharles93/archie-core/internal/eventbus"
arnats "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
)
// ── helpers ──────────────────────────────────────────────────────────
type mockRunner struct{}
func (m *mockRunner) Run(_ context.Context, _ string, req Request) (Result, error) {
return Result{
Version: ProtocolVersion,
TaskID: req.TaskID,
Attempt: req.Attempt,
Stage: req.Stage,
Status: StatusPassed,
Summary: "mock:" + req.Mission,
TokensUsed: 10,
Iterations: 1,
}, nil
}
var mockFactory = func(providers map[string]Provider, log *slog.Logger) Runner {
return &mockRunner{}
}
// ── regression: Gap 1 -- per-task agent ──────────────────────────────
func TestHandleMessageReadsWorkflowField(t *testing.T) {
// Gap 1: archie-agent is per-stage, not per-task.
// PRD section 1: when the daemon sends a task-level message with
// Workflow="implement" and Stages populated, the agent must run all
// stages as a batch. Single-stage mode (Request only) is the
// backward-compatible fallback.
ws := t.TempDir()
providers := map[string]Provider{"test": {Class: "openai", APIKeyEnv: "FAKE"}}
// Single-stage mode: uses Request, no Workflow, no Stages.
singleMsg := AgentRequestMessage{
TaskID: 1,
Attempt: 1,
Stage: "plan",
Workspace: ws,
Request: Request{
Version: ProtocolVersion, TaskID: 1, Attempt: 1,
Stage: "plan", Model: "test/model", Mission: "single",
Budget: Budget{MaxSteps: 1, MaxTokens: 10},
},
Providers: providers,
}
mockFactory := func(providers map[string]Provider, log *slog.Logger) Runner {
return &mockRunner{}
}
singleResp, err := HandleMessage(context.Background(), singleMsg, slog.New(slog.DiscardHandler), mockFactory)
if err != nil {
t.Fatal(err)
}
if singleResp.TaskCompleted {
t.Error("single-stage mode set TaskCompleted=true -- should be false")
}
// Per-task mode: Workflow set, Stages populated with two stages.
multiMsg := AgentRequestMessage{
TaskID: 2,
Attempt: 1,
Stage: "plan",
Workflow: "implement",
Workspace: ws,
Request: Request{
Version: ProtocolVersion, TaskID: 2, Attempt: 1,
Stage: "plan", Model: "test/model", Mission: "multi-1",
Budget: Budget{MaxSteps: 1, MaxTokens: 10},
},
Stages: []Request{
{
Version: ProtocolVersion, TaskID: 2, Attempt: 1,
Stage: "plan", Model: "test/model", Mission: "multi-plan",
Budget: Budget{MaxSteps: 1, MaxTokens: 10},
},
{
Version: ProtocolVersion, TaskID: 2, Attempt: 1,
Stage: "build", Model: "test/model", Mission: "multi-build",
Budget: Budget{MaxSteps: 1, MaxTokens: 10},
},
},
Providers: providers,
}
multiResp, err := HandleMessage(context.Background(), multiMsg, slog.New(slog.DiscardHandler), mockFactory)
if err != nil {
t.Fatal(err)
}
if !multiResp.TaskCompleted {
t.Error("Gap 1: per-task mode did not set TaskCompleted=true. " +
"The agent must signal task completion when all stages in a " +
"workflow batch have been processed.")
}
// Batch results must aggregate from both stages.
if multiResp.Result.TokensUsed == singleResp.Result.TokensUsed &&
multiResp.Result.Iterations == singleResp.Result.Iterations {
t.Error("Gap 1: per-task mode produced same token/iteration counts " +
"as single-stage mode. Multi-stage batch must accumulate " +
"results from all stages. See PRD section 1.")
}
}
// ── regression: Gap 3 -- response/system channel split ───────────────
func TestHandleMessageRoutesSystemMessagesSeparately(t *testing.T) {
// Gap 3: no response/system channel split.
// PRD section 2: system messages go to archie.agent.<id>.system and
// are never forwarded to humans. Response messages go to
// archie.agent.<id>.response for daemon review before human delivery.
// Currently HandleMessage always returns Channel="response" -- there
// is no code path that produces a system-channel response.
msg := AgentRequestMessage{
TaskID: 1,
Attempt: 1,
Stage: "plan",
Workspace: t.TempDir(),
Request: Request{
Version: ProtocolVersion,
TaskID: 1,
Attempt: 1,
Stage: "plan",
Model: "test/model",
Mission: "test",
Budget: Budget{MaxSteps: 1, MaxTokens: 10},
},
Providers: map[string]Provider{"test": {Class: "openai", APIKeyEnv: "FAKE"}},
}
// Normal stage request -- should route to response channel.
resp, err := HandleMessage(context.Background(), msg, slog.New(slog.DiscardHandler), mockFactory)
if err != nil {
t.Fatal(err)
}
if resp.Channel != "response" {
t.Errorf("normal stage request: Channel = %q, want \"response\"", resp.Channel)
}
// System message (health check, log dump request) -- should route to
// system channel. Currently HandleMessage always returns "response".
// The daemon sets Channel on the request to indicate message type.
msg.Channel = "system"
sysResp, err := HandleMessage(context.Background(), msg, slog.New(slog.DiscardHandler), mockFactory)
if err != nil {
t.Fatal(err)
}
if sysResp.Channel != "system" {
t.Error("Gap 3: HandleMessage ignores the input Channel field. " +
"When the daemon sends a system message (Channel=\"system\"), " +
"the response must be routed to archie.agent.<id>.system, " +
"not to the reply inbox. Currently all responses go to the " +
"same inbox regardless of channel. See PRD section 2.")
}
// Verify the subject functions exist and are distinct.
respSubj := SubjectForResponse(42)
sysSubj := SubjectForSystem(42)
if respSubj == sysSubj || respSubj == "" || sysSubj == "" {
t.Error("Gap 3: subject functions broken -- verify SubjectForAgentResponse " +
"and SubjectForAgentSystem return distinct, non-empty subjects.")
}
}
// ── existing tests ───────────────────────────────────────────────────
func startEmbeddedNATS(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.Fatalf("enable jetstream: %v", err)
}
return srv
}
func startHandler(t *testing.T, client *arnats.Client) {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
// Drain the client's own consumer rather than subscribing a second one:
// the stream uses work-queue retention, so two consumers with
// overlapping filter subjects conflict. This mirrors archie-agent.
go func() {
for ctx.Err() == nil {
msg, err := client.Fetch(ctx)
if err != nil {
continue
}
if err := replyToStage(ctx, client, msg); err != nil {
t.Errorf("stage handler: %v", err)
_ = msg.Nak()
continue
}
_ = msg.Ack()
}
}()
}
// replyToStage answers one stage request with a canned passing result.
func replyToStage(ctx context.Context, client *arnats.Client, msg eventbus.Message) error {
var req AgentRequestMessage
if err := json.Unmarshal(msg.Data(), &req); err != nil {
return err
}
replyTo, err := msg.ReplyAddress()
if err != nil {
return err
}
data, err := json.Marshal(AgentResponseEnvelope{
Version: req.Request.Version,
Result: Result{
Version: ProtocolVersion,
TaskID: req.TaskID,
Attempt: req.Attempt,
Stage: req.Stage,
Status: StatusPassed,
Summary: "handler-reply",
TokensUsed: 42,
},
})
if err != nil {
return err
}
return client.Respond(ctx, replyTo, data)
}
func TestNATSRunnerRoundTrip(t *testing.T) {
srv := startEmbeddedNATS(t)
url := srv.ClientURL()
ctx := context.Background()
client, err := arnats.Connect(ctx, arnats.Config{URL: url, Subjects: []string{workintake.SubjectTaskWildcard, SubjectAgentWildcard}, FilterSubject: SubjectAgentWildcard}, slog.New(slog.DiscardHandler))
if err != nil {
t.Fatal(err)
}
defer client.Close()
startHandler(t, client)
runner := &NATSRunner{
Bus: client,
Providers: map[string]Provider{"openai": {Class: "openai", APIKeyEnv: "TEST_KEY"}},
Log: slog.New(slog.DiscardHandler),
}
req := Request{
Version: ProtocolVersion,
TaskID: 42,
Attempt: 1,
Stage: "test",
Model: "openai/gpt",
Mission: "test mission",
Budget: Budget{MaxSteps: 5, MaxTokens: 100},
}
result, err := runner.Run(ctx, "/tmp/test-workspace", req)
if err != nil {
t.Fatal(err)
}
if result.Status != StatusPassed {
t.Fatalf("expected passed, got %s", result.Status)
}
if result.Summary != "handler-reply" {
t.Fatalf("expected 'handler-reply', got %q", result.Summary)
}
if result.TokensUsed != 42 {
t.Fatalf("expected 42 tokens, got %d", result.TokensUsed)
}
}