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.
This commit is contained in:
1 parent
2d082eef89
commit
a8efbf5046
11 files changed
+223
-73
No files matched your search
+1
-1
@@ -34,9 +34,9 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/forgerpc"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
|
||||
"github.com/samcharles93/archie-core/internal/memory"
|
||||
"github.com/samcharles93/archie-core/internal/memory/builtin"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
|
||||
"github.com/samcharles93/archie-core/internal/nell"
|
||||
"github.com/samcharles93/archie-core/internal/plugin"
|
||||
"github.com/samcharles93/archie-core/internal/plugin/pluginextract"
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
|
||||
arnats "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
|
||||
)
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
@@ -21,6 +22,18 @@ var knownFeatureNames = map[string]bool{
|
||||
"identities": true,
|
||||
}
|
||||
|
||||
// knownFeatureList renders the recognised feature names for error messages.
|
||||
// Derived from knownFeatureNames so the two cannot drift when a feature is
|
||||
// added.
|
||||
func knownFeatureList() string {
|
||||
names := make([]string, 0, len(knownFeatureNames))
|
||||
for name := range knownFeatureNames {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
return strings.Join(names, ", ")
|
||||
}
|
||||
|
||||
// LoadDir loads configuration from a directory tree.
|
||||
//
|
||||
// ~/.config/archie/config.yaml -- daemon-level fields
|
||||
@@ -102,29 +115,41 @@ func scanConfigEntries(dir string, entries []os.DirEntry) (mainYAML, mainTOML st
|
||||
case name == "config.toml":
|
||||
mainTOML = filepath.Join(dir, name)
|
||||
default:
|
||||
if uf := classifyFeatureFile(dir, name, featurePaths); uf != "" {
|
||||
unknownConfigFiles = append(unknownConfigFiles, uf)
|
||||
unknown, classifyErr := classifyFeatureFile(dir, name, featurePaths)
|
||||
if classifyErr != nil {
|
||||
return "", "", nil, nil, classifyErr
|
||||
}
|
||||
if unknown != "" {
|
||||
unknownConfigFiles = append(unknownConfigFiles, unknown)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(unknownConfigFiles) > 0 {
|
||||
return "", "", nil, nil, fmt.Errorf("unrecognized config file %q (known features: gateway, tools, memory, models, identities)", unknownConfigFiles[0])
|
||||
return "", "", nil, nil, fmt.Errorf("unrecognized config file %q (known features: %s)", unknownConfigFiles[0], knownFeatureList())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// classifyFeatureFile attempts to register a feature file in featurePaths.
|
||||
// Returns the filename if it is unrecognized, or "" on success/duplicate.
|
||||
func classifyFeatureFile(dir, name string, featurePaths map[string]string) string {
|
||||
// classifyFeatureFile registers a feature file in featurePaths.
|
||||
//
|
||||
// It returns the filename when the feature is unrecognised, so the caller can
|
||||
// report all such files together, and an error when two files claim the same
|
||||
// feature: silently preferring one would apply settings the operator cannot
|
||||
// see from the filenames alone.
|
||||
func classifyFeatureFile(dir, name string, featurePaths map[string]string) (string, error) {
|
||||
if !strings.HasPrefix(name, "config.") || (!strings.HasSuffix(name, ".yaml") && !strings.HasSuffix(name, ".yml")) {
|
||||
return ""
|
||||
return "", nil
|
||||
}
|
||||
feature := configFeatureName(name)
|
||||
if !knownFeatureNames[feature] {
|
||||
return name
|
||||
return name, nil
|
||||
}
|
||||
featurePaths[feature] = filepath.Join(dir, name)
|
||||
return ""
|
||||
path := filepath.Join(dir, name)
|
||||
if existing, ok := featurePaths[feature]; ok {
|
||||
return "", fmt.Errorf("duplicate feature %q: both %s and %s define it", feature, existing, path)
|
||||
}
|
||||
featurePaths[feature] = path
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func configFeatureName(filename string) string {
|
||||
|
||||
+33
-21
@@ -24,8 +24,8 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/container"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/memory"
|
||||
arnats "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
|
||||
"github.com/samcharles93/archie-core/internal/memory"
|
||||
"github.com/samcharles93/archie-core/internal/plugin"
|
||||
"github.com/samcharles93/archie-core/internal/storage"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
@@ -347,30 +347,22 @@ func (d *Daemon) drainNATS(ctx context.Context) {
|
||||
dispatcher := newTaskDispatcher(d.Cfg.Containers.MaxConcurrency, d.allowConcurrentFor)
|
||||
for ctx.Err() == nil {
|
||||
msg, err := d.Nats.Fetch(ctx)
|
||||
if errors.Is(err, arnats.ErrNoMessage) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
if err != nil && !errors.Is(err, arnats.ErrNoMessage) {
|
||||
d.Log.Error("nats fetch failed", "err", err)
|
||||
break
|
||||
}
|
||||
{
|
||||
tm, err := msg.Task()
|
||||
if err != nil {
|
||||
d.Log.Error("nats decode failed", "err", err)
|
||||
_ = msg.Ack() // bad message, don't retry
|
||||
continue
|
||||
}
|
||||
task := &store.Task{Owner: tm.Owner, Repo: tm.Repo}
|
||||
dispatcher.Submit(ctx, task, func(ctx context.Context, _ *store.Task) {
|
||||
d.processNATSTask(ctx, msg)
|
||||
})
|
||||
if err == nil {
|
||||
d.submitNATSTask(ctx, dispatcher, msg)
|
||||
continue
|
||||
}
|
||||
// Fall back to SQLite for requeued tasks.
|
||||
task, err := d.Store.ClaimNext(ctx)
|
||||
if err != nil {
|
||||
d.Log.Error("sqlite claim failed", "err", err)
|
||||
|
||||
// ErrNoMessage means the stream is drained. That is precisely when
|
||||
// the SQLite fallback must run: requeued tasks (waiting_human
|
||||
// approval, retry-parked) never went through a NATS publish, so
|
||||
// nothing will ever arrive on the stream to trigger them.
|
||||
task, claimErr := d.Store.ClaimNext(ctx)
|
||||
if claimErr != nil {
|
||||
d.Log.Error("sqlite claim failed", "err", claimErr)
|
||||
break
|
||||
}
|
||||
if task == nil {
|
||||
@@ -381,6 +373,22 @@ func (d *Daemon) drainNATS(ctx context.Context) {
|
||||
dispatcher.Wait()
|
||||
}
|
||||
|
||||
// submitNATSTask decodes a fetched message and queues it for processing. A
|
||||
// message that cannot be decoded is acked rather than redelivered: it will
|
||||
// never decode on a retry, so leaving it unacked would block the queue.
|
||||
func (d *Daemon) submitNATSTask(ctx context.Context, dispatcher *taskDispatcher, msg arnats.Message) {
|
||||
envelope, err := msg.Task()
|
||||
if err != nil {
|
||||
d.Log.Error("nats decode failed", "subject", msg.Subject(), "err", err)
|
||||
_ = msg.Ack()
|
||||
return
|
||||
}
|
||||
task := &store.Task{Owner: envelope.Owner, Repo: envelope.Repo}
|
||||
dispatcher.Submit(ctx, task, func(ctx context.Context, _ *store.Task) {
|
||||
d.processNATSTask(ctx, msg)
|
||||
})
|
||||
}
|
||||
|
||||
// taskDispatcher bounds task execution globally while preserving the default
|
||||
// one-task-per-repository safety rule. Submit order is retained within a repo;
|
||||
// tasks for different repos may run concurrently. Repos for which
|
||||
@@ -497,14 +505,18 @@ func (d *Daemon) pollNATS(ctx context.Context, fg forge.Forge, repo config.Repo,
|
||||
d.maybeRetryParked(ctx, repo, is)
|
||||
return
|
||||
}
|
||||
// Classify here, not in the bus: the label vocabulary belongs to the
|
||||
// workflow package, which routes on the same kinds.
|
||||
parsed := workflow.SplitLabels(labels)
|
||||
if err := d.Nats.PublishTask(ctx, arnats.TaskEnvelope{
|
||||
Owner: repo.Owner,
|
||||
Repo: repo.Name,
|
||||
Number: is.Number,
|
||||
Title: is.Title,
|
||||
Body: is.Body,
|
||||
Labels: strings.Split(labels, ","),
|
||||
Labels: parsed,
|
||||
Identity: identity,
|
||||
Kind: arnats.TaskKind(workflow.KindForLabels(parsed)),
|
||||
}); err != nil {
|
||||
d.Log.Error("nats publish failed", "repo", repo.FullName(), "issue", is.Number, "err", err)
|
||||
return
|
||||
|
||||
@@ -355,7 +355,9 @@ func TestRunViaAgentRetriesUntilResponderAppears(t *testing.T) {
|
||||
time.Sleep(80 * time.Millisecond)
|
||||
coreConn, connErr := d.Nats.CoreConn()
|
||||
if connErr != nil {
|
||||
t.Fatalf("CoreConn: %v", connErr)
|
||||
// Fatalf from a non-test goroutine does not stop the test.
|
||||
t.Errorf("CoreConn: %v", connErr)
|
||||
return
|
||||
}
|
||||
sub, err := coreConn.Subscribe(taskrun.SubjectForTask(task.ID), func(msg *natsio.Msg) {
|
||||
data, _ := json.Marshal(taskrun.Response{Status: store.StatusPROpen})
|
||||
|
||||
@@ -21,4 +21,8 @@ var (
|
||||
|
||||
// ErrInvalidConfig reports a Config that cannot produce a usable client.
|
||||
ErrInvalidConfig = errors.New("nats: invalid configuration")
|
||||
|
||||
// ErrUnknownTaskKind reports a publish whose TaskKind has no subject.
|
||||
// Routing to the default queue instead would silently misdeliver work.
|
||||
ErrUnknownTaskKind = errors.New("nats: unknown task kind")
|
||||
)
|
||||
@@ -33,6 +33,11 @@ type TaskEnvelope struct {
|
||||
// empty for single-identity deployments. Carried so the consuming daemon
|
||||
// enqueues the task under the right owner.
|
||||
Identity string `json:"identity,omitempty"`
|
||||
|
||||
// Kind is the routing category, chosen by the publisher. Empty means
|
||||
// TaskKindDefault, which is also what messages queued before this field
|
||||
// existed decode to.
|
||||
Kind TaskKind `json:"kind,omitempty"`
|
||||
}
|
||||
|
||||
// taskEnvelopeWire avoids infinite recursion in the JSON methods below.
|
||||
@@ -66,7 +71,7 @@ func (t TaskEnvelope) DedupKey() string {
|
||||
}
|
||||
|
||||
// Subject returns the task subject this envelope routes to.
|
||||
func (t TaskEnvelope) Subject() string { return SubjectForLabels(t.Labels) }
|
||||
func (t TaskEnvelope) Subject() string { return SubjectForKind(t.Kind) }
|
||||
|
||||
// splitLabels parses the comma-separated wire form, dropping empty entries so
|
||||
// "bug,,feature" and a trailing comma do not produce blank labels.
|
||||
|
||||
@@ -8,10 +8,14 @@ import (
|
||||
"github.com/nats-io/nats.go"
|
||||
)
|
||||
|
||||
// PublishTask publishes a discovered issue to the subject its labels select.
|
||||
// PublishTask publishes a discovered issue to the subject its kind selects.
|
||||
// The dedup header suppresses republishing the same issue inside the
|
||||
// configured dedup window.
|
||||
func (c *Client) PublishTask(ctx context.Context, task TaskEnvelope) error {
|
||||
if err := task.Kind.Validate(); err != nil {
|
||||
return fmt.Errorf("publish task %s/%s#%d: %w", task.Owner, task.Repo, task.Number, err)
|
||||
}
|
||||
|
||||
data, err := json.Marshal(task)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode task %s/%s#%d: %w", task.Owner, task.Repo, task.Number, err)
|
||||
@@ -27,6 +31,7 @@ func (c *Client) PublishTask(ctx context.Context, task TaskEnvelope) error {
|
||||
|
||||
c.log.Debug("published task",
|
||||
"subject", subject,
|
||||
"kind", string(task.Kind),
|
||||
"owner", task.Owner,
|
||||
"repo", task.Repo,
|
||||
"number", task.Number,
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
package nats
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
import "fmt"
|
||||
|
||||
// Task distribution subjects. Each encodes the workflow type so a multi-daemon
|
||||
// deployment can filter by workflow.
|
||||
@@ -24,23 +21,53 @@ const (
|
||||
// message's Reply field for its own PubAck, so the address travels as a header.
|
||||
const ReplyHeader = "X-Archie-Reply"
|
||||
|
||||
// labelSubjects maps an issue label to its task subject. Declared once so the
|
||||
// mapping is data rather than a switch, and so SubjectForLabels and any future
|
||||
// reverse lookup cannot drift apart.
|
||||
var labelSubjects = map[string]string{
|
||||
"bug": SubjectTaskBug,
|
||||
"feature": SubjectTaskFeature,
|
||||
"bootstrap": SubjectTaskBootstrap,
|
||||
// TaskKind is the routing token in a task subject.
|
||||
//
|
||||
// The bus deliberately does not derive this itself. It previously inspected
|
||||
// forge issue labels to choose a subject, which put a forge vocabulary
|
||||
// ("bug", "feature") inside infrastructure and duplicated the label table
|
||||
// already owned by the workflow package. The publisher now decides the kind
|
||||
// and the bus only renders it as a subject.
|
||||
type TaskKind string
|
||||
|
||||
const (
|
||||
TaskKindBug TaskKind = "bug"
|
||||
TaskKindFeature TaskKind = "feature"
|
||||
TaskKindBootstrap TaskKind = "bootstrap"
|
||||
|
||||
// TaskKindDefault carries tasks that match no more specific kind.
|
||||
TaskKindDefault TaskKind = "default"
|
||||
)
|
||||
|
||||
// taskSubjects is the closed set of routable kinds. A kind absent from this
|
||||
// map has no subject, so publishing it is a caller error rather than a
|
||||
// silent delivery to the default queue.
|
||||
var taskSubjects = map[TaskKind]string{
|
||||
TaskKindBug: SubjectTaskBug,
|
||||
TaskKindFeature: SubjectTaskFeature,
|
||||
TaskKindBootstrap: SubjectTaskBootstrap,
|
||||
TaskKindDefault: SubjectTaskDefault,
|
||||
}
|
||||
|
||||
// SubjectForLabels picks the task subject for a set of issue labels, mirroring
|
||||
// the label-to-workflow mapping in workflow.Route. The first recognised label
|
||||
// wins; unrecognised or empty label sets route to SubjectTaskDefault.
|
||||
func SubjectForLabels(labels []string) string {
|
||||
for _, label := range labels {
|
||||
if subject, ok := labelSubjects[strings.TrimSpace(label)]; ok {
|
||||
return subject
|
||||
}
|
||||
// Validate reports whether the kind is routable. The zero kind is accepted
|
||||
// and means TaskKindDefault, so callers that do not classify still publish.
|
||||
func (k TaskKind) Validate() error {
|
||||
if k == "" {
|
||||
return nil
|
||||
}
|
||||
if _, ok := taskSubjects[k]; !ok {
|
||||
return fmt.Errorf("%w: %q", ErrUnknownTaskKind, string(k))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SubjectForKind renders a kind as its task subject. The zero and any
|
||||
// unrecognised kind render as SubjectTaskDefault so a message is never
|
||||
// published to an unroutable subject; PublishTask rejects unknown kinds
|
||||
// before reaching here.
|
||||
func SubjectForKind(kind TaskKind) string {
|
||||
if subject, ok := taskSubjects[kind]; ok {
|
||||
return subject
|
||||
}
|
||||
return SubjectTaskDefault
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package workflow
|
||||
|
||||
import "strings"
|
||||
|
||||
// Kind is the routing category an issue's labels select.
|
||||
//
|
||||
// It is the single axis both the workflow registry and the event bus route
|
||||
// on. Before this existed the label table was written twice -- once here as
|
||||
// a switch in Route, once in the NATS package as a subject lookup -- so
|
||||
// adding a label meant remembering both, and the event bus had to know what
|
||||
// a forge label was.
|
||||
type Kind string
|
||||
|
||||
const (
|
||||
KindBug Kind = "bug"
|
||||
KindFeature Kind = "feature"
|
||||
KindBootstrap Kind = "bootstrap"
|
||||
|
||||
// KindDefault is the routing category for issues carrying no
|
||||
// recognised label.
|
||||
KindDefault Kind = "default"
|
||||
)
|
||||
|
||||
// labelKinds maps a forge issue label to its routing kind. This is the one
|
||||
// place the label vocabulary is defined.
|
||||
var labelKinds = map[string]Kind{
|
||||
"bug": KindBug,
|
||||
"feature": KindFeature,
|
||||
"bootstrap": KindBootstrap,
|
||||
}
|
||||
|
||||
// kindWorkflows names the registry entry each kind prefers. Bootstrap
|
||||
// exercises the full pipeline deterministically (no LLM spend) -- invites,
|
||||
// clone, push, PR, labels.
|
||||
var kindWorkflows = map[Kind]string{
|
||||
KindBug: "tdd",
|
||||
KindFeature: "feasibility",
|
||||
KindBootstrap: "bootstrap",
|
||||
}
|
||||
|
||||
// KindForLabels returns the routing kind for a set of issue labels. The
|
||||
// first recognised label wins; an empty or unrecognised set is KindDefault.
|
||||
func KindForLabels(labels []string) Kind {
|
||||
for _, kind := range KindsForLabels(labels) {
|
||||
return kind
|
||||
}
|
||||
return KindDefault
|
||||
}
|
||||
|
||||
// KindsForLabels returns every recognised kind in label order.
|
||||
//
|
||||
// Route needs the full ordered set rather than just the first: when a task
|
||||
// is labelled "bug,feature" and no "tdd" workflow is registered, it must
|
||||
// still fall through to "feasibility" rather than to the default.
|
||||
func KindsForLabels(labels []string) []Kind {
|
||||
var kinds []Kind
|
||||
for _, label := range labels {
|
||||
if kind, ok := labelKinds[strings.TrimSpace(label)]; ok {
|
||||
kinds = append(kinds, kind)
|
||||
}
|
||||
}
|
||||
return kinds
|
||||
}
|
||||
|
||||
// SplitLabels parses the comma-separated label form used on store.Task,
|
||||
// dropping blanks so "bug,," and a trailing comma do not yield empty labels.
|
||||
func SplitLabels(raw string) []string {
|
||||
if raw == "" {
|
||||
return nil
|
||||
}
|
||||
parts := strings.Split(raw, ",")
|
||||
labels := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
if trimmed := strings.TrimSpace(part); trimmed != "" {
|
||||
labels = append(labels, trimmed)
|
||||
}
|
||||
}
|
||||
if len(labels) == 0 {
|
||||
return nil
|
||||
}
|
||||
return labels
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
@@ -151,23 +150,13 @@ func Route(t *store.Task, reg Registry) Workflow {
|
||||
return wf
|
||||
}
|
||||
}
|
||||
labels := strings.SplitSeq(t.Labels, ",")
|
||||
for l := range labels {
|
||||
switch strings.TrimSpace(l) {
|
||||
case "bug":
|
||||
if wf, ok := reg["tdd"]; ok {
|
||||
return wf
|
||||
}
|
||||
case "feature":
|
||||
if wf, ok := reg["feasibility"]; ok {
|
||||
return wf
|
||||
}
|
||||
case "bootstrap":
|
||||
// Diagnostics: exercise the full pipeline deterministically
|
||||
// (no LLM spend) -- invites, clone, push, PR, labels.
|
||||
if wf, ok := reg["bootstrap"]; ok {
|
||||
return wf
|
||||
}
|
||||
for _, kind := range KindsForLabels(SplitLabels(t.Labels)) {
|
||||
name, ok := kindWorkflows[kind]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if wf, ok := reg[name]; ok {
|
||||
return wf
|
||||
}
|
||||
}
|
||||
if wf, ok := reg["implement"]; ok {
|
||||
|
||||
Reference in new issue
Block a user