Files
archie/internal/agentexec/nats.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

127 lines
4.1 KiB
Go

package agentexec
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"time"
"github.com/samcharles93/archie-core/internal/eventbus"
)
// AgentRequestMessage is the NATS payload for an agent stage execution request.
// When Workflow is set and Stages is populated, the agent runs all stages as a
// per-task batch rather than a single stage. PRD §1.
type AgentRequestMessage struct {
TaskID int64 `json:"task_id"`
Attempt int `json:"attempt"`
Stage string `json:"stage"`
Workflow string `json:"workflow,omitempty"`
Channel string `json:"channel,omitempty"` // "response" (default) or "system"
Workspace string `json:"workspace"`
Request Request `json:"request"`
Stages []Request `json:"stages,omitempty"` // batch: all agent stages for this task
Providers map[string]Provider `json:"providers,omitempty"`
}
// AgentResponseEnvelope is the response payload published to the reply inbox.
type AgentResponseEnvelope struct {
Version int `json:"version"`
Result Result `json:"result"`
Error string `json:"error,omitempty"`
Channel string `json:"channel,omitempty"` // "response" (default) or "system"
TaskCompleted bool `json:"task_completed,omitempty"` // true when all stages finished (per-task mode)
}
const defaultAgentTimeout = 30 * time.Minute
// 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 {
Bus RequestBus
Providers map[string]Provider
Log *slog.Logger
}
// Run publishes a stage execution request to JetStream with an X-Archie-Reply
// header, blocks on the sync inbox subscription, and returns the result.
func (r *NATSRunner) Run(ctx context.Context, workspace string, req Request) (Result, error) {
if err := req.Validate(); err != nil {
return Result{}, err
}
// 1. Create reply inbox with auto-unsubscribe after one message.
replySub, err := r.Bus.NewReplyInbox()
if err != nil {
return Result{}, fmt.Errorf("nats reply inbox: %w", err)
}
defer func() {
if err := replySub.Close(); err != nil {
r.Log.Warn("reply inbox close failed", "err", err)
}
}()
// 2. Compute timeout from budget.
timeout := defaultAgentTimeout
if req.Budget.WallClock > 0 {
timeout = req.Budget.WallClock
}
// 3. Publish request with reply header.
msg := AgentRequestMessage{
TaskID: req.TaskID,
Attempt: req.Attempt,
Stage: req.Stage,
Workflow: req.Workflow,
Workspace: workspace,
Request: req,
Providers: r.Providers,
}
data, err := json.Marshal(msg)
if err != nil {
return Result{}, err
}
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)
}
// 4. Wait for reply (blocking, matching SubprocessRunner.Run behaviour).
replyCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
reply, err := replySub.Next(replyCtx)
if err != nil {
return Result{}, fmt.Errorf("agent reply: %w", err)
}
// 5. Decode response.
var envelope AgentResponseEnvelope
if err := json.Unmarshal(reply, &envelope); err != nil {
return Result{}, fmt.Errorf("decode agent response: %w", err)
}
if envelope.Error != "" {
return envelope.Result, errors.New(envelope.Error)
}
if err := envelope.Result.ValidateFor(req); err != nil {
return envelope.Result, err
}
return envelope.Result, nil
}