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.
This commit is contained in:
sam committed 2026-07-29 11:40:24 +10:00
1 parent 69dce53bfd
commit 9d5040fd65
23 files changed
+787 -600

No files matched your search

+21 -7
View File
@@ -8,7 +8,7 @@ import (
"log/slog"
"time"
arnats "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
"github.com/samcharles93/archie-core/internal/eventbus"
)
// AgentRequestMessage is the NATS payload for an agent stage execution request.
@@ -37,10 +37,24 @@ type AgentResponseEnvelope struct {
const defaultAgentTimeout = 30 * time.Minute
// NATSRunner sends agent stage execution requests over NATS JetStream and
// waits for replies on core NATS inboxes. It implements Runner.
// RequestBus is the messaging this runner needs: publish a request carrying a
// reply address, and create the inbox that address points at.
//
// Declared here rather than taking eventbus.Bus because a domain defines the
// smallest interface required to do its work -- this runner never fetches or
// subscribes, and should not be able to.
type RequestBus interface {
PublishRequest(ctx context.Context, subject, replyTo string, payload []byte) error
NewReplyInbox() (eventbus.ReplyInbox, error)
}
// NATSRunner sends agent stage execution requests over the bus and waits for
// replies on a one-shot inbox. It implements Runner.
//
// The name is historical: it holds no NATS type and works with any bus
// satisfying RequestBus.
type NATSRunner struct {
Nats *arnats.Client
Bus RequestBus
Providers map[string]Provider
Log *slog.Logger
}
@@ -53,7 +67,7 @@ func (r *NATSRunner) Run(ctx context.Context, workspace string, req Request) (Re
}
// 1. Create reply inbox with auto-unsubscribe after one message.
replySub, err := r.Nats.NewReplyInbox()
replySub, err := r.Bus.NewReplyInbox()
if err != nil {
return Result{}, fmt.Errorf("nats reply inbox: %w", err)
}
@@ -84,8 +98,8 @@ func (r *NATSRunner) Run(ctx context.Context, workspace string, req Request) (Re
return Result{}, err
}
subject := arnats.SubjectForAgentRequest(req.TaskID)
if err := r.Nats.PublishRequest(ctx, subject, replySub.Subject(), data); err != nil {
subject := SubjectForRequest(req.TaskID)
if err := r.Bus.PublishRequest(ctx, subject, replySub.Subject(), data); err != nil {
return Result{}, fmt.Errorf("publish agent request: %w", err)
}
+50 -67
View File
@@ -5,13 +5,12 @@ import (
"encoding/json"
"log/slog"
"testing"
"time"
"github.com/nats-io/nats-server/v2/server"
natssrv "github.com/nats-io/nats-server/v2/test"
natsio "github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
"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"
)
@@ -169,8 +168,8 @@ func TestHandleMessageRoutesSystemMessagesSeparately(t *testing.T) {
}
// Verify the subject functions exist and are distinct.
respSubj := arnats.SubjectForAgentResponse(42)
sysSubj := arnats.SubjectForAgentSystem(42)
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.")
@@ -189,78 +188,73 @@ func startEmbeddedNATS(t *testing.T) *server.Server {
return srv
}
func startHandler(t *testing.T, nc *natsio.Conn) {
func startHandler(t *testing.T, client *arnats.Client) {
t.Helper()
js, err := jetstream.New(nc)
if err != nil {
t.Fatal(err)
}
stream, err := js.CreateOrUpdateStream(context.Background(), jetstream.StreamConfig{
Name: "ARCHIE_TASKS",
Subjects: []string{"archie.task.>", "archie.agent.>"},
Storage: jetstream.FileStorage,
Retention: jetstream.WorkQueuePolicy,
})
if err != nil {
t.Fatal(err)
}
cons, err := stream.CreateOrUpdateConsumer(context.Background(), jetstream.ConsumerConfig{
Name: "test-agent",
FilterSubject: arnats.SubjectAgentWildcard,
AckPolicy: jetstream.AckExplicitPolicy,
MaxDeliver: 1,
})
if err != nil {
t.Fatal(err)
}
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 {
batch, err := cons.Fetch(1, jetstream.FetchMaxWait(5*time.Second))
for ctx.Err() == nil {
msg, err := client.Fetch(ctx)
if err != nil {
return
continue
}
for msg := range batch.Messages() {
if msg == nil {
continue
}
var req AgentRequestMessage
_ = json.Unmarshal(msg.Data(), &req)
replyTo := msg.Headers().Get(arnats.ReplyHeader)
resp := 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,
},
}
data, _ := json.Marshal(resp)
_ = nc.Publish(replyTo, data)
_ = msg.Ack()
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}, slog.New(slog.DiscardHandler))
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, mustCoreConn(t, client))
startHandler(t, client)
runner := &NATSRunner{
Nats: client,
Bus: client,
Providers: map[string]Provider{"openai": {Class: "openai", APIKeyEnv: "TEST_KEY"}},
Log: slog.New(slog.DiscardHandler),
}
@@ -289,14 +283,3 @@ func TestNATSRunnerRoundTrip(t *testing.T) {
t.Fatalf("expected 42 tokens, got %d", result.TokensUsed)
}
}
// mustCoreConn returns the raw NATS connection for tests that drive core-NATS
// subscriptions directly, failing the test if the client is not connected.
func mustCoreConn(t *testing.T, c *arnats.Client) *natsio.Conn {
t.Helper()
conn, err := c.CoreConn()
if err != nil {
t.Fatalf("CoreConn: %v", err)
}
return conn
}
+45
View File
@@ -0,0 +1,45 @@
package agentexec
import "strconv"
// Agent execution subjects.
//
// These belong to this package because it defines what an agent request and
// response mean. They previously sat in the NATS package, which made the
// transport the owner of Archie's agent protocol; see
// docs/architecture/dependencies-and-contracts.md -- message schemas and the
// subjects addressing them stay with the domain that defines them.
//
// The stage travels in the payload, not the subject: one subject per task
// carrying sequential stage messages.
const (
// SubjectAgentWildcard matches every agent subject.
SubjectAgentWildcard = "archie.agent.>"
subjectAgentPrefix = "archie.agent."
)
// SubjectForRequest returns the subject carrying stage execution requests for
// a task.
func SubjectForRequest(taskID int64) string {
return subjectForTask(taskID, "request")
}
// SubjectForResponse returns the subject for agent output destined for human
// channels. The daemon reviews these before forwarding to issue comments,
// labels, or pull requests.
func SubjectForResponse(taskID int64) string {
return subjectForTask(taskID, "response")
}
// SubjectForSystem returns the subject for internal agent messages such as
// log dumps, health, and PII warnings. The daemon reads these for
// observability and never forwards them.
func SubjectForSystem(taskID int64) string {
return subjectForTask(taskID, "system")
}
// subjectForTask builds a per-task agent subject.
func subjectForTask(taskID int64, kind string) string {
return subjectAgentPrefix + strconv.FormatInt(taskID, 10) + "." + kind
}