Files
archie/cmd/archie-agent/main.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

235 lines
7.1 KiB
Go

// Command archie-agent is a long-running NATS-connected worker. It answers
// two request shapes: single-stage archie.agent.> requests over the
// ARCHIE_TASKS JetStream stream (the legacy per-stage protocol), and full
// task handoffs on archie.taskrun.> (core NATS, queue-grouped) -- where it
// runs workflow.Route/workflow.Run itself, proxying Store/Forge/worktree
// operations back to archied over NATS instead of holding those
// credentials directly.
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"log/slog"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"github.com/nats-io/nats.go"
"github.com/samcharles93/archie-core/internal/agentexec"
"github.com/samcharles93/archie-core/internal/container"
"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"
"github.com/samcharles93/archie-core/internal/storage"
"github.com/samcharles93/archie-core/internal/taskrun"
)
const (
consumerName = "archie-agent"
pollTimeout = 5 * time.Second
// ackWait exceeds the longest stage runtime: a stage still working must
// not have its message redelivered to another worker.
ackWait = 30 * time.Minute
// taskRunSubjectWildcard matches full-task handoffs (archie.taskrun.<id>).
// A queue group means only one archie-agent instance answers each
// message, whether deployed as a shared worker pool (today) or spawned
// one-per-task (the sandboxed container target).
taskRunSubjectWildcard = "archie.taskrun.>"
taskRunQueueGroup = "archie-taskrun-workers"
)
func main() {
os.Exit(run())
}
func run() int {
natsURLFlag := flag.String("nats-url", "", "NATS server URL (defaults to NATS_URL)")
consumer := flag.String("consumer", consumerName, "JetStream consumer name")
flag.Parse()
natsURL, natsToken := natsConnectionSettings(*natsURLFlag, os.Getenv)
if natsURL == "" {
fmt.Fprintln(os.Stderr, "error: -nats-url or NATS_URL is required")
flag.Usage()
return 1
}
log := slog.New(slog.NewJSONHandler(os.Stderr, nil))
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// One bus client owns the stream definition. archied declares the same
// stream with the same subjects; this process previously declared its
// own copy, free to disagree about retention, dedup window and TTLs.
bus, err := arnats.Connect(ctx, arnats.Config{
URL: natsURL,
Token: natsToken,
Subjects: []string{workintake.SubjectTaskWildcard, agentexec.SubjectAgentWildcard},
ConsumerName: *consumer,
FilterSubject: agentexec.SubjectAgentWildcard,
PollTimeout: pollTimeout,
AckWait: ackWait,
}, log)
if err != nil {
log.Error("nats connect failed", "err", err)
return 1
}
defer bus.Close()
// Full-task handoffs use core NATS request/reply with a queue group,
// which the JetStream contract does not express.
nc, err := bus.CoreConn()
if err != nil {
log.Error("nats connection unavailable", "err", err)
return 1
}
// Subscribe to task run messages.
taskRunSub, err := subscribeTaskRuns(ctx, nc, log)
if err != nil {
log.Error("taskrun subscribe failed", "err", err)
return 1
}
defer func() {
if err := taskRunSub.Unsubscribe(); err != nil {
log.Warn("task run unsubscribe failed", "err", err)
}
}()
log.Info("archie-agent ready", "nats", natsURL, "consumer", *consumer)
return runMainLoop(ctx, bus, log)
}
// subscribeTaskRuns prefers a dedicated per-task subscription over the
// shared queue group whenever this container was spawned for a specific
// task (task.json present at the worktree mount).
func subscribeTaskRuns(ctx context.Context, nc *nats.Conn, log *slog.Logger) (*nats.Subscription, error) {
if taskID, ok := bootTaskID(storage.WorktreeMountDir, log); ok {
log.Info("taskrun: dedicated per-task subscription", "task", taskID)
return nc.Subscribe(taskrun.SubjectForTask(taskID), func(msg *nats.Msg) {
handleTaskRun(ctx, msg, nc, log)
})
}
log.Info("taskrun: shared queue-group subscription (no task.json found)")
return nc.QueueSubscribe(taskRunSubjectWildcard, taskRunQueueGroup, func(msg *nats.Msg) {
handleTaskRun(ctx, msg, nc, log)
})
}
// bootTaskID reads the boot-time task.json brief the daemon writes into
// the worktree before container acquire (container.WriteTaskJSON) and
// returns its ID. Returns (0, false) when the file is absent, unparseable,
// or has no ID -- any of which mean "shared pool mode, no dedicated task."
func bootTaskID(mountDir string, log *slog.Logger) (int64, bool) {
data, err := os.ReadFile(filepath.Join(mountDir, "task.json"))
if err != nil {
return 0, false
}
var payload container.TaskPayload
if err := json.Unmarshal(data, &payload); err != nil {
log.Warn("task.json present but unparseable -- falling back to shared queue subscription", "err", err)
return 0, false
}
if payload.ID <= 0 {
return 0, false
}
return payload.ID, true
}
// stageBus is the messaging this loop needs: pull the next stage request and
// answer it on the requester's inbox.
type stageBus interface {
Fetch(ctx context.Context) (eventbus.Message, error)
Respond(ctx context.Context, replyAddress string, payload []byte) error
}
// runMainLoop runs the fetch-handle-ack loop until the context is cancelled.
func runMainLoop(ctx context.Context, bus stageBus, log *slog.Logger) int {
for {
if ctx.Err() != nil {
log.Info("archie-agent shutting down")
return 0
}
msg, err := bus.Fetch(ctx)
switch {
case errors.Is(err, eventbus.ErrNoMessage):
continue
case err != nil:
if ctx.Err() != nil {
return 0
}
log.Error("fetch failed", "err", err)
time.Sleep(1 * time.Second)
continue
}
if err := handle(ctx, msg, bus, log); err != nil {
log.Error("handle failed", "err", err)
if err := msg.Nak(); err != nil {
log.Warn("nak failed", "err", err)
}
continue
}
if err := msg.Ack(); err != nil {
log.Warn("ack failed", "err", err)
}
}
}
func natsConnectionSettings(flagURL string, getenv func(string) string) (url, token string) {
url = flagURL
if url == "" {
url = getenv("NATS_URL")
}
return url, getenv("NATS_TOKEN")
}
func handle(ctx context.Context, msg eventbus.Message, bus stageBus, log *slog.Logger) error {
var req agentexec.AgentRequestMessage
if err := json.Unmarshal(msg.Data(), &req); err != nil {
return fmt.Errorf("decode request: %w", err)
}
replyTo, err := msg.ReplyAddress()
if err != nil {
return fmt.Errorf("stage request on %s: %w", msg.Subject(), err)
}
log.Info("processing stage",
"task", req.TaskID,
"attempt", req.Attempt,
"stage", req.Stage,
"workflow", req.Workflow,
"reply_to", replyTo,
)
resp, err := agentexec.HandleMessage(ctx, req, log, agentexec.DefaultRunnerFactory)
if err != nil {
return fmt.Errorf("handle: %w", err)
}
data, err := json.Marshal(resp)
if err != nil {
return fmt.Errorf("encode response: %w", err)
}
if err := bus.Respond(ctx, replyTo, data); err != nil {
return fmt.Errorf("publish response: %w", err)
}
log.Info("stage complete",
"task", req.TaskID,
"stage", req.Stage,
"status", resp.Result.Status,
)
return nil
}