Files
archie/internal/agentexec/nats.go
T
sam a8efbf5046 refactor: route tasks on a typed kind, not forge labels
The event bus was inspecting forge issue labels ("bug", "feature",
"bootstrap") to pick a subject. That put a forge vocabulary inside
infrastructure and duplicated the label table already owned by
workflow.Route -- adding a label meant remembering both places, and
nothing would have caught it if you forgot.

The label table now lives once, in internal/workflow, which already owns
label semantics:

  - workflow.Kind names the routing category, with labelKinds as the
    single label vocabulary and kindWorkflows mapping kind to registry
    entry. Route consumes the ordered kind list so a "bug,feature" task
    still falls through to feasibility when no tdd workflow is
    registered, exactly as the switch did.
  - nats.TaskKind is a closed, validated set of subject tokens.
    PublishTask rejects an unknown kind rather than silently delivering
    it to the default queue; the zero kind means default, so messages
    queued before this field decode unchanged.
  - The daemon classifies at the publish site and sets TaskEnvelope.Kind.

Also fixes two defects this exposed:

  - drainNATS never reached its SQLite fallback. Replacing the old
    (nil, nil) no-message signal with ErrNoMessage in 492ca20 made that
    case continue at the top of the loop, but no-message is precisely
    when the fallback must run -- requeued tasks (waiting_human approval,
    retry-parked) never go through a NATS publish, so nothing would ever
    arrive to trigger them. go vet caught it as unreachable code.
  - config.classifyFeatureFile silently overwrote duplicate feature
    files, so config.gateway.yaml and conf.d/gateway.yaml together
    applied one at random. Its own doc comment recorded the bug
    ("or "" on success/duplicate"). The known-feature list in the error
    message is now derived from knownFeatureNames instead of being
    spelled out a second time beside it.

A test also called t.Fatalf from a non-test goroutine, where it does not
stop the test.

Verified: go build, go vet, gofmt clean. Pre-existing gateway (18) and
telegram (1) failures are unchanged in count -- they are lost routing
wiring from the parallel telegram merges, tracked separately.
2026-07-29 10:43:52 +10:00

113 lines
3.6 KiB
Go

package agentexec
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"time"
arnats "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
)
// 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
// NATSRunner sends agent stage execution requests over NATS JetStream and
// waits for replies on core NATS inboxes. It implements Runner.
type NATSRunner struct {
Nats *arnats.Client
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.Nats.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 := arnats.SubjectForAgentRequest(req.TaskID)
if err := r.Nats.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
}