refactor(agent): move worker runtime into application layer
cmd/archie-agent used to own worker construction, NATS lifecycle, task execution, MCP setup, and workflow wiring. It now owns process input only and invokes internal/app/agentworker, while transport-specific NATS, boot-brief, and git-safety mechanics live under infrastructure.
This commit is contained in:
1 parent
0243c13d37
commit
45345cdfb6
35 files changed
+2901
-689
No files matched your search
@@ -0,0 +1,108 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCommandBoundary(t *testing.T) {
|
||||
paths, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, path := range paths {
|
||||
if !strings.HasSuffix(path, "_test.go") && path != "main.go" {
|
||||
t.Errorf("cmd/archie-agent contains substantive production file %q; runtime ownership belongs in internal/app/agentworker", path)
|
||||
}
|
||||
}
|
||||
|
||||
file, err := parser.ParseFile(token.NewFileSet(), "main.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
const (
|
||||
projectInternal = "github.com/samcharles93/archie-core/internal/"
|
||||
appImport = projectInternal + "app/agentworker"
|
||||
)
|
||||
appIdent := "agentworker"
|
||||
for _, imported := range file.Imports {
|
||||
path, err := strconv.Unquote(imported.Path.Value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.HasPrefix(path, projectInternal) && path != appImport {
|
||||
t.Errorf("cmd/archie-agent imports substantive internal package %q; only %q is allowed", path, appImport)
|
||||
}
|
||||
if path == appImport && imported.Name != nil {
|
||||
if imported.Name.Name == "." || imported.Name.Name == "_" {
|
||||
t.Errorf("cmd/archie-agent imports %q with unsupported alias %q", appImport, imported.Name.Name)
|
||||
} else {
|
||||
appIdent = imported.Name.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
allowedFunctions := map[string]bool{
|
||||
"main": true,
|
||||
"run": true,
|
||||
"runCommand": true,
|
||||
"natsConnectionSettings": true,
|
||||
}
|
||||
for _, declaration := range file.Decls {
|
||||
function, ok := declaration.(*ast.FuncDecl)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if function.Recv != nil || !allowedFunctions[function.Name.Name] {
|
||||
t.Errorf("cmd/archie-agent main.go declares unexpected function %q; orchestration belongs in internal/app/agentworker", function.Name.Name)
|
||||
}
|
||||
delete(allowedFunctions, function.Name.Name)
|
||||
}
|
||||
for name := range allowedFunctions {
|
||||
t.Errorf("cmd/archie-agent main.go is missing intended process function %q", name)
|
||||
}
|
||||
|
||||
var runFunction *ast.FuncDecl
|
||||
for _, declaration := range file.Decls {
|
||||
function, ok := declaration.(*ast.FuncDecl)
|
||||
if ok && function.Name.Name == "run" {
|
||||
runFunction = function
|
||||
break
|
||||
}
|
||||
}
|
||||
if runFunction == nil {
|
||||
t.Fatal("cmd/archie-agent has no run function")
|
||||
}
|
||||
|
||||
workerCalls := 0
|
||||
ast.Inspect(runFunction.Body, func(node ast.Node) bool {
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
callee, ok := call.Fun.(*ast.Ident)
|
||||
if !ok || callee.Name != "runCommand" {
|
||||
return true
|
||||
}
|
||||
for _, argument := range call.Args {
|
||||
selector, ok := argument.(*ast.SelectorExpr)
|
||||
if !ok || selector.Sel.Name != "Run" {
|
||||
continue
|
||||
}
|
||||
pkg, ok := selector.X.(*ast.Ident)
|
||||
if ok && pkg.Name == appIdent {
|
||||
workerCalls++
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
if workerCalls != 1 {
|
||||
t.Fatalf("cmd/archie-agent run passes agentworker.Run to runCommand %d times, want exactly 1", workerCalls)
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// gitRunner runs a git invocation and returns its combined output. Injected so
|
||||
// the safe.directory configuration can be tested without a git binary.
|
||||
type gitRunner func(ctx context.Context, args ...string) ([]byte, error)
|
||||
|
||||
// runGit is the production gitRunner.
|
||||
func runGit(ctx context.Context, args ...string) ([]byte, error) {
|
||||
return exec.CommandContext(ctx, "git", args...).CombinedOutput()
|
||||
}
|
||||
|
||||
// markWorktreeSafe adds mountDir to git's global safe.directory list.
|
||||
//
|
||||
// The daemon bind-mounts the task worktree into the container from the host,
|
||||
// so the directory is owned by a UID the container user is not. Git refuses to
|
||||
// operate in a repository it does not own ("detected dubious ownership"), and
|
||||
// the Go toolchain shells out to git for VCS stamping during build/test/vet --
|
||||
// so without this every gate fails before the agent does any real work.
|
||||
//
|
||||
// Best-effort by design: git may be absent from a minimal image, and an agent
|
||||
// working a repo with no gate commands never needs it. A failure is logged and
|
||||
// the agent continues. Returns true only when git accepted the configuration.
|
||||
//
|
||||
// The mount is checked first so that running archie-agent directly on a host
|
||||
// (shared queue-group mode, no container) does not write to the operator's own
|
||||
// ~/.gitconfig for a path that was never mounted.
|
||||
func markWorktreeSafe(ctx context.Context, mountDir string, run gitRunner, log *slog.Logger) bool {
|
||||
info, err := os.Stat(mountDir)
|
||||
if err != nil || !info.IsDir() {
|
||||
log.Debug("git safe.directory skipped: no worktree mounted", "dir", mountDir)
|
||||
return false
|
||||
}
|
||||
|
||||
out, err := run(ctx, "config", "--global", "--add", "safe.directory", mountDir)
|
||||
if err != nil {
|
||||
log.Warn("git safe.directory config failed -- gates that shell out to git may fail",
|
||||
"dir", mountDir,
|
||||
"err", err,
|
||||
"output", strings.TrimSpace(string(out)),
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
log.Info("git safe.directory configured", "dir", mountDir)
|
||||
return true
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMainConfiguresWorktreeSafetyOnce(t *testing.T) {
|
||||
file, err := parser.ParseFile(token.NewFileSet(), "main.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var markCalls, inlineCalls int
|
||||
ast.Inspect(file, func(node ast.Node) bool {
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
if ident, ok := call.Fun.(*ast.Ident); ok && ident.Name == "markWorktreeSafe" {
|
||||
markCalls++
|
||||
}
|
||||
for _, arg := range call.Args {
|
||||
literal, ok := arg.(*ast.BasicLit)
|
||||
if ok && literal.Kind == token.STRING && literal.Value == `"safe.directory"` {
|
||||
inlineCalls++
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
if markCalls != 1 {
|
||||
t.Fatalf("main.go calls markWorktreeSafe %d times, want 1", markCalls)
|
||||
}
|
||||
if got := markCalls + inlineCalls; got != 1 {
|
||||
t.Fatalf("main.go configures safe.directory %d times, want one authoritative setup path", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarkWorktreeSafe(t *testing.T) {
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
|
||||
present := func(t *testing.T) string { t.Helper(); return t.TempDir() }
|
||||
absent := func(t *testing.T) string { t.Helper(); return t.TempDir() + "/never-mounted" }
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
mountDir func(t *testing.T) string
|
||||
runErr error
|
||||
want bool
|
||||
wantRuns int
|
||||
}{
|
||||
{
|
||||
name: "configures git when the worktree is mounted",
|
||||
mountDir: present,
|
||||
want: true,
|
||||
wantRuns: 1,
|
||||
},
|
||||
{
|
||||
name: "git failure is best-effort",
|
||||
mountDir: present,
|
||||
runErr: errors.New("exit status 1"),
|
||||
want: false,
|
||||
wantRuns: 1,
|
||||
},
|
||||
{
|
||||
name: "git missing is best-effort",
|
||||
mountDir: present,
|
||||
runErr: errors.New(`exec: "git": executable file not found in $PATH`),
|
||||
want: false,
|
||||
wantRuns: 1,
|
||||
},
|
||||
{
|
||||
name: "no mounted worktree leaves git config untouched",
|
||||
mountDir: absent,
|
||||
want: false,
|
||||
wantRuns: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := tc.mountDir(t)
|
||||
var runs [][]string
|
||||
run := func(_ context.Context, args ...string) ([]byte, error) {
|
||||
runs = append(runs, args)
|
||||
return []byte("output"), tc.runErr
|
||||
}
|
||||
|
||||
got := markWorktreeSafe(context.Background(), dir, run, log)
|
||||
|
||||
if got != tc.want {
|
||||
t.Fatalf("markWorktreeSafe() = %v, want %v", got, tc.want)
|
||||
}
|
||||
if len(runs) != tc.wantRuns {
|
||||
t.Fatalf("git invoked %d times, want %d (%v)", len(runs), tc.wantRuns, runs)
|
||||
}
|
||||
if tc.wantRuns == 0 {
|
||||
return
|
||||
}
|
||||
wantArgs := []string{"config", "--global", "--add", "safe.directory", dir}
|
||||
if !reflect.DeepEqual(runs[0], wantArgs) {
|
||||
t.Fatalf("git args = %v, want %v", runs[0], wantArgs)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A mount path that is a file, not a directory, is not a worktree: git must
|
||||
// not be reconfigured for it.
|
||||
func TestMarkWorktreeSafeIgnoresNonDirectory(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
file := filepath.Join(dir, "worktree")
|
||||
if err := os.WriteFile(file, []byte("not a worktree"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
invoked := false
|
||||
run := func(_ context.Context, _ ...string) ([]byte, error) {
|
||||
invoked = true
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if got := markWorktreeSafe(context.Background(), file, run, slog.New(slog.DiscardHandler)); got {
|
||||
t.Fatal("markWorktreeSafe() = true for a non-directory mount path, want false")
|
||||
}
|
||||
if invoked {
|
||||
t.Fatal("git was invoked for a non-directory mount path")
|
||||
}
|
||||
}
|
||||
+29
-375
@@ -1,230 +1,63 @@
|
||||
// Command archie-agent is a long-running NATS-connected worker. It answers
|
||||
// two independent request shapes that serve different deployment modes:
|
||||
//
|
||||
// 1. Single-stage requests on archie.agent.> over the ARCHIE_TASKS
|
||||
// JetStream stream -- used when agent.mode is "nats" without
|
||||
// container sandboxing. One stage is dispatched per message, and the
|
||||
// agent replies on the caller's inbox.
|
||||
//
|
||||
// 2. Full-task handoffs on archie.taskrun.> (core NATS, queue-grouped)
|
||||
// -- used with Docker container sandboxing. The agent runs
|
||||
// workflow.Route/workflow.Run itself, proxying Store/Forge/worktree
|
||||
// operations back to archied over NATS instead of holding those
|
||||
// credentials directly.
|
||||
// Command archie-agent runs Archie's NATS-connected agent worker.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"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"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
"github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
toolprovider "github.com/samcharles93/archie-core/internal/tools/provider"
|
||||
mcptoolprovider "github.com/samcharles93/archie-core/internal/tools/provider/mcp"
|
||||
"github.com/samcharles93/archie-core/internal/app/agentworker"
|
||||
)
|
||||
|
||||
const (
|
||||
consumerName = "archie-agent"
|
||||
pollTimeout = 5 * time.Second
|
||||
const consumerName = "archie-agent"
|
||||
|
||||
// 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"
|
||||
)
|
||||
type workerRunner func(context.Context, agentworker.Settings, *slog.Logger) error
|
||||
|
||||
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()
|
||||
return runCommand(os.Args[1:], os.Getenv, os.Stderr, agentworker.Run)
|
||||
}
|
||||
|
||||
natsURL, natsToken := natsConnectionSettings(*natsURLFlag, os.Getenv)
|
||||
func runCommand(args []string, getenv func(string) string, stderr io.Writer, runWorker workerRunner) int {
|
||||
flags := flag.NewFlagSet("archie-agent", flag.ContinueOnError)
|
||||
flags.SetOutput(stderr)
|
||||
natsURLFlag := flags.String("nats-url", "", "NATS server URL (defaults to NATS_URL)")
|
||||
consumer := flags.String("consumer", consumerName, "JetStream consumer name")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return 0
|
||||
}
|
||||
return 2
|
||||
}
|
||||
|
||||
natsURL, natsToken := natsConnectionSettings(*natsURLFlag, getenv)
|
||||
if natsURL == "" {
|
||||
fmt.Fprintln(os.Stderr, "error: -nats-url or NATS_URL is required")
|
||||
flag.Usage()
|
||||
fmt.Fprintln(stderr, "error: -nats-url or NATS_URL is required")
|
||||
flags.Usage()
|
||||
return 1
|
||||
}
|
||||
|
||||
log := slog.New(slog.NewJSONHandler(os.Stderr, nil))
|
||||
|
||||
log := slog.New(slog.NewJSONHandler(stderr, nil))
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
// Before anything can run a gate: the worktree is a host bind mount owned
|
||||
// by another UID, and git refuses to work in it until it is marked safe.
|
||||
markWorktreeSafe(ctx, storage.WorktreeMountDir, runGit, log)
|
||||
|
||||
// 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)
|
||||
if err := runWorker(ctx, agentworker.Settings{
|
||||
NATSURL: natsURL,
|
||||
NATSToken: natsToken,
|
||||
Consumer: *consumer,
|
||||
}, log); err != nil {
|
||||
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
|
||||
}
|
||||
|
||||
// A dedicated per-task subscription (below) means this container was
|
||||
// spawned for one task, which is also when its stderr is otherwise
|
||||
// unrecoverable: container.Pool creates it with AutoRemove: true. Once
|
||||
// nc exists, ship this process's own logs to the daemon over
|
||||
// SubjectForSystem(taskID) so they survive the container's exit. Shared
|
||||
// queue-group mode serves many unrelated tasks per process, so there is
|
||||
// no single task subject to ship to -- it keeps the stderr-only logger.
|
||||
//
|
||||
// This only covers logging done through the `log` variable from here on.
|
||||
// bus (arnats.Client) was constructed above with the pre-wrap logger and
|
||||
// keeps it for its own lifetime, so its own wire-activity Debug lines
|
||||
// (e.g. "published" on every bus.Respond) stay stderr-only regardless.
|
||||
// That's a real, known gap, not an oversight: it's the bus's internal
|
||||
// chatter about NATS itself, not the agent's own reasoning or tool
|
||||
// output, and reordering construction to close it would mean connecting
|
||||
// to NATS before knowing whether NATS is even needed for this call.
|
||||
taskID, hasTaskID := bootTaskID(storage.WorktreeMountDir, log)
|
||||
if hasTaskID {
|
||||
log = slog.New(agentexec.NewSystemLogHandler(log.Handler(), nc, taskID))
|
||||
log.Info("system log publisher attached", "task", taskID)
|
||||
}
|
||||
|
||||
// Subscribe to task run messages.
|
||||
taskRunSub, err := subscribeTaskRuns(ctx, nc, log, taskID, hasTaskID)
|
||||
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. taskID/hasTaskID come from bootTaskID (.git/task.json present at the
|
||||
// worktree mount) -- the caller resolves it once, since it also decides
|
||||
// whether to attach a per-task log publisher to log before this is called.
|
||||
func subscribeTaskRuns(ctx context.Context, nc *nats.Conn, log *slog.Logger, taskID int64, hasTaskID bool) (*nats.Subscription, error) {
|
||||
if hasTaskID {
|
||||
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 .git/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. It lives under .git so the agent's own commit can't sweep
|
||||
// it onto the task branch. 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, ".git", "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)
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func natsConnectionSettings(flagURL string, getenv func(string) string) (url, token string) {
|
||||
@@ -234,182 +67,3 @@ func natsConnectionSettings(flagURL string, getenv func(string) string) (url, to
|
||||
}
|
||||
return url, getenv("NATS_TOKEN")
|
||||
}
|
||||
|
||||
// mcpProviderSet holds the resources needed to clean up MCP providers.
|
||||
type mcpProviderSet struct {
|
||||
providers []toolprovider.Engine
|
||||
registry *tools.Registry
|
||||
}
|
||||
|
||||
// startMCPProviders creates MCP transports from config, starts them,
|
||||
// discovers tools, and registers them into a local registry. Returns
|
||||
// nil when there are no servers configured.
|
||||
func startMCPProviders(ctx context.Context, servers []config.MCPServer, log *slog.Logger) (*mcpProviderSet, error) {
|
||||
if len(servers) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
reg := tools.NewRegistry()
|
||||
var providers []toolprovider.Engine
|
||||
var firstErr error
|
||||
|
||||
for _, srv := range servers {
|
||||
name := strings.TrimSpace(srv.Name)
|
||||
if name == "" {
|
||||
log.Warn("mcp server skipped: empty name")
|
||||
continue
|
||||
}
|
||||
transportType := strings.ToLower(strings.TrimSpace(srv.Transport))
|
||||
if transportType == "" {
|
||||
transportType = "stdio"
|
||||
}
|
||||
|
||||
var transport mcptoolprovider.LifecycleTransport
|
||||
switch transportType {
|
||||
case "stdio":
|
||||
command := strings.TrimSpace(srv.Command)
|
||||
if command == "" {
|
||||
err := fmt.Errorf("MCP stdio server %q requires a command", name)
|
||||
log.Warn("mcp server skipped", "name", name, "err", err)
|
||||
if firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
continue
|
||||
}
|
||||
transport = mcp.NewStdioTransport(mcp.StdioTransportConfig{
|
||||
Command: command,
|
||||
Args: append([]string(nil), srv.Args...),
|
||||
})
|
||||
case "http", "streamablehttp":
|
||||
url := strings.TrimSpace(srv.URL)
|
||||
if url == "" {
|
||||
err := fmt.Errorf("MCP http server %q requires a url", name)
|
||||
log.Warn("mcp server skipped", "name", name, "err", err)
|
||||
if firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
continue
|
||||
}
|
||||
transport = mcp.NewHTTPTransport(mcp.HTTPTransportConfig{
|
||||
Endpoint: url,
|
||||
Headers: srv.Headers,
|
||||
})
|
||||
case "sse":
|
||||
sseEndpoint := strings.TrimSpace(srv.SSEEndpoint)
|
||||
if sseEndpoint == "" {
|
||||
err := fmt.Errorf("MCP sse server %q requires an sse_endpoint", name)
|
||||
log.Warn("mcp server skipped", "name", name, "err", err)
|
||||
if firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
continue
|
||||
}
|
||||
transport = mcp.NewSSETransport(mcp.SSETransportConfig{
|
||||
SSEEndpoint: sseEndpoint,
|
||||
MessageEndpoint: strings.TrimSpace(srv.MessageEndpoint),
|
||||
Headers: srv.Headers,
|
||||
})
|
||||
default:
|
||||
log.Warn("mcp server skipped: unknown transport", "name", name, "transport", transportType)
|
||||
continue
|
||||
}
|
||||
|
||||
provider := mcptoolprovider.New(name, transport)
|
||||
if err := provider.Start(ctx); err != nil {
|
||||
log.Warn("mcp provider start failed", "name", name, "err", err)
|
||||
if firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
entries, err := provider.Discover(ctx)
|
||||
if err != nil {
|
||||
log.Warn("mcp tool discovery failed", "name", name, "err", err)
|
||||
// Stop the provider since we can't use it.
|
||||
_ = provider.Stop(ctx)
|
||||
if firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
if err := reg.Register(entry); err != nil {
|
||||
log.Warn("mcp tool registration failed", "tool", entry.Name, "err", err)
|
||||
}
|
||||
}
|
||||
providers = append(providers, provider)
|
||||
log.Info("mcp provider started", "name", name, "transport", transportType, "tools", len(entries))
|
||||
}
|
||||
|
||||
if len(providers) == 0 {
|
||||
return nil, firstErr
|
||||
}
|
||||
return &mcpProviderSet{providers: providers, registry: reg}, nil
|
||||
}
|
||||
|
||||
func (s *mcpProviderSet) cleanup(ctx context.Context, log *slog.Logger) {
|
||||
for _, p := range s.providers {
|
||||
if err := p.Stop(ctx); err != nil {
|
||||
log.Warn("mcp provider stop failed", "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
// Start MCP providers and build a local tool registry.
|
||||
mcpSet, mcpErr := startMCPProviders(ctx, req.MCPServers, log)
|
||||
if mcpSet != nil {
|
||||
defer mcpSet.cleanup(ctx, log)
|
||||
}
|
||||
if mcpErr != nil {
|
||||
log.Warn("mcp providers had errors, continuing with available tools", "err", mcpErr)
|
||||
}
|
||||
|
||||
// Build a runner factory that includes MCP-discovered tools.
|
||||
factory := func(providers map[string]agentexec.Provider, log *slog.Logger) agentexec.Runner {
|
||||
var registries []*tools.Registry
|
||||
if mcpSet != nil {
|
||||
registries = append(registries, mcpSet.registry)
|
||||
}
|
||||
return agentexec.NewInProcessRunner(agentexec.NewRuntime(providers), log, registries...)
|
||||
}
|
||||
|
||||
resp, err := agentexec.HandleMessage(ctx, req, log, factory)
|
||||
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
|
||||
}
|
||||
@@ -1,73 +1,107 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/container"
|
||||
"github.com/samcharles93/archie-core/internal/app/agentworker"
|
||||
)
|
||||
|
||||
// gitDir returns a temp mount dir with the .git directory the daemon writes
|
||||
// the boot brief into.
|
||||
func gitDir(t *testing.T) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(dir, ".git"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
func TestRunCommandPreservesCLIExitSemantics(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
getenv func(string) string
|
||||
worker workerRunner
|
||||
wantCode int
|
||||
}{
|
||||
{name: "help", args: []string{"-h"}},
|
||||
{name: "flag parse error", args: []string{"-unknown"}, wantCode: 2},
|
||||
{name: "missing NATS URL", wantCode: 1},
|
||||
{
|
||||
name: "worker failure",
|
||||
args: []string{"-nats-url", "nats://test"},
|
||||
worker: func(context.Context, agentworker.Settings, *slog.Logger) error {
|
||||
return errors.New("worker failed")
|
||||
},
|
||||
wantCode: 1,
|
||||
},
|
||||
{
|
||||
name: "success",
|
||||
args: []string{"-nats-url", "nats://test"},
|
||||
worker: func(context.Context, agentworker.Settings, *slog.Logger) error {
|
||||
return nil
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
getenv := test.getenv
|
||||
if getenv == nil {
|
||||
getenv = func(string) string { return "" }
|
||||
}
|
||||
worker := test.worker
|
||||
if worker == nil {
|
||||
worker = func(context.Context, agentworker.Settings, *slog.Logger) error {
|
||||
t.Fatal("worker called")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if got := runCommand(test.args, getenv, &bytes.Buffer{}, worker); got != test.wantCode {
|
||||
t.Fatalf("runCommand() = %d, want %d", got, test.wantCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
func TestBootTaskID(t *testing.T) {
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
|
||||
t.Run("no task.json -- shared pool mode", func(t *testing.T) {
|
||||
id, ok := bootTaskID(t.TempDir(), log)
|
||||
if ok || id != 0 {
|
||||
t.Fatalf("bootTaskID() = (%d, %v), want (0, false)", id, ok)
|
||||
}
|
||||
func TestRunCommandRequiresNATSURL(t *testing.T) {
|
||||
var stderr bytes.Buffer
|
||||
called := false
|
||||
code := runCommand(nil, func(string) string { return "" }, &stderr, func(context.Context, agentworker.Settings, *slog.Logger) error {
|
||||
called = true
|
||||
return nil
|
||||
})
|
||||
if code != 1 || called {
|
||||
t.Fatalf("(code, worker called) = (%d, %v), want (1, false)", code, called)
|
||||
}
|
||||
for _, want := range []string{"error: -nats-url or NATS_URL is required", "Usage of archie-agent:"} {
|
||||
if !strings.Contains(stderr.String(), want) {
|
||||
t.Fatalf("stderr %q does not contain %q", stderr.String(), want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("valid task.json -- dedicated per-task mode", func(t *testing.T) {
|
||||
dir := gitDir(t)
|
||||
data, err := json.Marshal(container.TaskPayload{ID: 42, Owner: "acme", Repo: "widget"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, ".git", "task.json"), data, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, ok := bootTaskID(dir, log)
|
||||
if !ok || id != 42 {
|
||||
t.Fatalf("bootTaskID() = (%d, %v), want (42, true)", id, ok)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("malformed task.json falls back to shared pool mode", func(t *testing.T) {
|
||||
dir := gitDir(t)
|
||||
if err := os.WriteFile(filepath.Join(dir, ".git", "task.json"), []byte("not json"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, ok := bootTaskID(dir, log)
|
||||
if ok || id != 0 {
|
||||
t.Fatalf("bootTaskID() = (%d, %v), want (0, false)", id, ok)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("zero ID falls back to shared pool mode", func(t *testing.T) {
|
||||
dir := gitDir(t)
|
||||
data, _ := json.Marshal(container.TaskPayload{Owner: "acme", Repo: "widget"})
|
||||
if err := os.WriteFile(filepath.Join(dir, ".git", "task.json"), data, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, ok := bootTaskID(dir, log)
|
||||
if ok || id != 0 {
|
||||
t.Fatalf("bootTaskID() = (%d, %v), want (0, false)", id, ok)
|
||||
}
|
||||
})
|
||||
func TestRunCommandMapsWorkerOutcomeToExitStatus(t *testing.T) {
|
||||
workerErr := errors.New("startup failed")
|
||||
tests := []struct {
|
||||
name string
|
||||
workerErr error
|
||||
wantCode int
|
||||
}{
|
||||
{name: "success"},
|
||||
{name: "worker failure", workerErr: workerErr, wantCode: 1},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var stderr bytes.Buffer
|
||||
code := runCommand([]string{"-nats-url", "nats://flag", "-consumer", "custom"}, func(string) string { return "token" }, &stderr, func(_ context.Context, settings agentworker.Settings, _ *slog.Logger) error {
|
||||
if settings.NATSURL != "nats://flag" || settings.NATSToken != "token" || settings.Consumer != "custom" {
|
||||
t.Fatalf("settings = %#v", settings)
|
||||
}
|
||||
return test.workerErr
|
||||
})
|
||||
if code != test.wantCode {
|
||||
t.Fatalf("code = %d, want %d", code, test.wantCode)
|
||||
}
|
||||
if test.workerErr != nil && stderr.Len() != 0 {
|
||||
t.Fatalf("stderr = %q, want command not to duplicate application logging", stderr.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNATSConnectionSettings(t *testing.T) {
|
||||
|
||||
@@ -1,174 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/skillbuild"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/wfeval"
|
||||
"github.com/samcharles93/archie-core/internal/forgerpc"
|
||||
"github.com/samcharles93/archie-core/internal/storage"
|
||||
"github.com/samcharles93/archie-core/internal/storerpc"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
"github.com/samcharles93/archie-core/internal/worktreerpc"
|
||||
)
|
||||
|
||||
const rpcTimeout = 60 * time.Second
|
||||
|
||||
// hybridTrees implements workflow.Trees by splitting operations: Prepare
|
||||
// and Push (network ops needing the daemon's forge credential) proxy over
|
||||
// worktreerpc; CommitAll/Diff/ChangedFiles/ChangedLines are local git
|
||||
// operations run directly against the container's bind-mounted worktree.
|
||||
//
|
||||
// Prepare deliberately discards the RPC response's directory (the
|
||||
// daemon's host-side path) and returns localDir instead -- archied and
|
||||
// archie-agent see the same files at different paths.
|
||||
type hybridTrees struct {
|
||||
push *worktreerpc.Client
|
||||
local *worktree.Manager
|
||||
owner, repo string
|
||||
issue int
|
||||
localDir string
|
||||
}
|
||||
|
||||
func (h *hybridTrees) Prepare(ctx context.Context, owner, repo, base string, issue int, title, body, labels string) (dir, branch string, err error) {
|
||||
_, branch, err = h.push.Prepare(ctx, owner, repo, base, issue, title, body, labels)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return h.localDir, branch, nil
|
||||
}
|
||||
|
||||
func (h *hybridTrees) CommitAll(ctx context.Context, dir, message string) (bool, error) {
|
||||
return h.local.CommitAll(ctx, dir, message)
|
||||
}
|
||||
|
||||
func (h *hybridTrees) Push(ctx context.Context, dir, branch string) error {
|
||||
return h.push.Push(ctx, h.owner, h.repo, h.issue, branch)
|
||||
}
|
||||
|
||||
func (h *hybridTrees) Diff(ctx context.Context, dir, base string) (string, error) {
|
||||
return h.local.Diff(ctx, dir, base)
|
||||
}
|
||||
|
||||
func (h *hybridTrees) ChangedFiles(ctx context.Context, dir, base string) ([]string, error) {
|
||||
return h.local.ChangedFiles(ctx, dir, base)
|
||||
}
|
||||
|
||||
func (h *hybridTrees) ChangedLines(ctx context.Context, dir, base string) (int, error) {
|
||||
return h.local.ChangedLines(ctx, dir, base)
|
||||
}
|
||||
|
||||
var _ workflow.Trees = (*hybridTrees)(nil)
|
||||
|
||||
// runTask builds a workflow.Registry from the container's own mounted
|
||||
// worktree, routes and runs req.Task's entire workflow, and reports the
|
||||
// terminal outcome. Store/Forge/worktree-push calls proxy back to archied
|
||||
// over nc; Store is archied's sole authority for task state -- the
|
||||
// returned Response.Task is a best-effort snapshot for logging only.
|
||||
func runTask(ctx context.Context, req taskrun.Request, nc *natsio.Conn, newRunner agentexec.RunnerFactory, workDir string, log *slog.Logger) (*taskrun.Response, error) {
|
||||
registry, err := skillbuild.BuildRegistry(workDir)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build registry: %w", err)
|
||||
}
|
||||
|
||||
wf := workflow.Route(req.Task, registry)
|
||||
|
||||
trees := &hybridTrees{
|
||||
push: &worktreerpc.Client{Conn: nc, Timeout: rpcTimeout, Identity: req.Task.Identity},
|
||||
local: &worktree.Manager{WorkDir: workDir},
|
||||
owner: req.Task.Owner,
|
||||
repo: req.Task.Repo,
|
||||
issue: req.Task.IssueNumber,
|
||||
localDir: workDir,
|
||||
}
|
||||
|
||||
// Start MCP providers and build a local tool registry.
|
||||
mcpSet, mcpErr := startMCPProviders(ctx, req.MCPServers, log)
|
||||
if mcpSet != nil {
|
||||
defer mcpSet.cleanup(ctx, log)
|
||||
}
|
||||
if mcpErr != nil {
|
||||
log.Warn("mcp providers had errors, continuing with available tools", "err", mcpErr)
|
||||
}
|
||||
|
||||
// Build a runner with MCP-discovered tools when available.
|
||||
var agent agentexec.Runner
|
||||
if mcpSet != nil && mcpSet.registry != nil {
|
||||
agent = agentexec.NewInProcessRunner(agentexec.NewRuntime(req.Providers), log, mcpSet.registry)
|
||||
} else {
|
||||
agent = newRunner(req.Providers, log)
|
||||
}
|
||||
if agent == nil {
|
||||
return nil, fmt.Errorf("no agent runner configured for task %d", req.Task.ID)
|
||||
}
|
||||
|
||||
tc := &workflow.TaskContext{
|
||||
Task: req.Task,
|
||||
Repo: req.Repo,
|
||||
Cfg: req.Cfg.ToConfig(),
|
||||
Forge: &forgerpc.Client{Conn: nc, Timeout: rpcTimeout, Identity: req.Task.Identity},
|
||||
Store: &storerpc.Client{Conn: nc, Timeout: rpcTimeout},
|
||||
Trees: trees,
|
||||
Agent: agent,
|
||||
Log: log,
|
||||
CustomStages: wfeval.Discover,
|
||||
}
|
||||
|
||||
workflow.Run(ctx, wf, tc)
|
||||
|
||||
return &taskrun.Response{
|
||||
Task: tc.Task,
|
||||
Status: tc.Outcome.Status,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// handleTaskRun decodes a taskrun.Request from msg, runs it via runTask
|
||||
// against the container's fixed worktree mount, and replies with the
|
||||
// outcome. Errors are reported in the reply, not returned -- there's no
|
||||
// caller to return them to; this is a NATS subscription callback.
|
||||
func handleTaskRun(ctx context.Context, msg *natsio.Msg, nc *natsio.Conn, log *slog.Logger) {
|
||||
var req taskrun.Request
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
log.Error("taskrun decode failed", "err", err)
|
||||
respondTaskRun(msg, nil, fmt.Errorf("decode taskrun request: %w", err), log)
|
||||
return
|
||||
}
|
||||
|
||||
log.Info("running task", "task", req.Task.ID, "repo", req.Repo.FullName(), "issue", req.Task.IssueNumber)
|
||||
|
||||
resp, err := runTask(ctx, req, nc, agentexec.DefaultRunnerFactory, storage.WorktreeMountDir, log)
|
||||
if err != nil {
|
||||
log.Error("task run failed", "task", req.Task.ID, "err", err)
|
||||
respondTaskRun(msg, nil, err, log)
|
||||
return
|
||||
}
|
||||
|
||||
log.Info("task run complete", "task", req.Task.ID, "status", resp.Status)
|
||||
respondTaskRun(msg, resp, nil, log)
|
||||
}
|
||||
|
||||
func respondTaskRun(msg *natsio.Msg, resp *taskrun.Response, runErr error, log *slog.Logger) {
|
||||
if resp == nil {
|
||||
resp = &taskrun.Response{}
|
||||
}
|
||||
if runErr != nil {
|
||||
resp.Error = runErr.Error()
|
||||
}
|
||||
data, err := json.Marshal(resp)
|
||||
if err != nil {
|
||||
log.Error("taskrun encode response failed", "err", err)
|
||||
return
|
||||
}
|
||||
if err := msg.Respond(data); err != nil {
|
||||
log.Error("taskrun respond failed", "err", err)
|
||||
}
|
||||
}
|
||||
@@ -1,237 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"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/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/forgerpc"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/storerpc"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
"github.com/samcharles93/archie-core/internal/worktreerpc"
|
||||
)
|
||||
|
||||
func startEmbeddedForTaskRun(t *testing.T) *server.Server {
|
||||
t.Helper()
|
||||
srv := natssrv.RunRandClientPortServer()
|
||||
t.Cleanup(srv.Shutdown)
|
||||
return srv
|
||||
}
|
||||
|
||||
func connectForTaskRun(t *testing.T, url string) *natsio.Conn {
|
||||
t.Helper()
|
||||
nc, err := natsio.Connect(url)
|
||||
if err != nil {
|
||||
t.Fatalf("nats connect: %v", err)
|
||||
}
|
||||
t.Cleanup(nc.Close)
|
||||
return nc
|
||||
}
|
||||
|
||||
// panicRunner fails the test if the bootstrap workflow (deterministic,
|
||||
// no LLM stages) ever invokes it.
|
||||
type panicRunner struct{ t *testing.T }
|
||||
|
||||
func (r panicRunner) Run(context.Context, string, agentexec.Request) (agentexec.Result, error) {
|
||||
r.t.Fatal("bootstrap workflow must not invoke an LLM runner")
|
||||
return agentexec.Result{}, nil
|
||||
}
|
||||
|
||||
// prCapturingForge records CreatePR calls and answers the four Forger
|
||||
// methods the bootstrap workflow needs; everything else panics.
|
||||
type prCapturingForge struct {
|
||||
prs []struct{ owner, repo, title, head, base, body string }
|
||||
}
|
||||
|
||||
func (f *prCapturingForge) Comment(context.Context, string, string, int, string) (int64, error) {
|
||||
return 1, nil
|
||||
}
|
||||
func (f *prCapturingForge) CloseIssue(context.Context, string, string, int, string) error { return nil }
|
||||
func (f *prCapturingForge) CreatePR(_ context.Context, owner, repo, title, head, base, body string) (int, error) {
|
||||
f.prs = append(f.prs, struct{ owner, repo, title, head, base, body string }{owner, repo, title, head, base, body})
|
||||
return 5, nil
|
||||
}
|
||||
func (f *prCapturingForge) SetStateLabel(context.Context, string, string, int, string, []string) {}
|
||||
func (f *prCapturingForge) AcceptInvitations(context.Context) error { panic("unexpected call") }
|
||||
func (f *prCapturingForge) AssignedIssues(context.Context, string, string, string) ([]forge.Issue, error) {
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
func (f *prCapturingForge) IssuesWithLabel(context.Context, string, string, string) ([]forge.Issue, error) {
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
func (f *prCapturingForge) RepliesAfter(context.Context, string, string, int, int64, string) ([]forge.Reply, error) {
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
func (f *prCapturingForge) PRState(context.Context, string, string, int) (string, error) {
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
func (f *prCapturingForge) CreateIssue(context.Context, string, string, string, string, []string) (int, error) {
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
func (f *prCapturingForge) React(context.Context, string, string, int, string) error {
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
func (f *prCapturingForge) VerifyPush(context.Context, string, string) error {
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
func (f *prCapturingForge) LinkBranch(context.Context, string, string, int, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// newLocalRemote mirrors worktree_test.go's helper: a bare repo with one
|
||||
// commit on main, reachable via file://<host>/<owner>/<repo>.git.
|
||||
func newLocalRemote(t *testing.T, owner, repo string) string {
|
||||
t.Helper()
|
||||
host := t.TempDir()
|
||||
bare := filepath.Join(host, owner, repo+".git")
|
||||
seed := filepath.Join(t.TempDir(), "seed")
|
||||
|
||||
run := func(dir string, args ...string) {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0")
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("git %v: %v\n%s", args, err, out)
|
||||
}
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(bare, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run(host, "init", "--bare", "-b", "main", bare)
|
||||
if err := os.MkdirAll(seed, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run(seed, "init", "-b", "main")
|
||||
run(seed, "config", "user.name", "seeder")
|
||||
run(seed, "config", "user.email", "seed@example.com")
|
||||
if err := os.WriteFile(filepath.Join(seed, "README.md"), []byte("seed\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run(seed, "add", "-A")
|
||||
run(seed, "commit", "-m", "seed")
|
||||
run(seed, "push", "file://"+bare, "main")
|
||||
return host
|
||||
}
|
||||
|
||||
// TestRunTaskExecutesBootstrapWorkflowEndToEnd drives runTask through the
|
||||
// deterministic "bootstrap" workflow (no LLM calls) with real storerpc/
|
||||
// forgerpc/worktreerpc servers backing an RPC-constructed TaskContext,
|
||||
// proving the full archie-agent-side wiring: registry build, Route, Run,
|
||||
// and the hybrid Trees split between proxied Prepare/Push and local git.
|
||||
func TestRunTaskExecutesBootstrapWorkflowEndToEnd(t *testing.T) {
|
||||
if _, err := exec.LookPath("git"); err != nil {
|
||||
t.Skip("git not installed")
|
||||
}
|
||||
ctx := context.Background()
|
||||
host := newLocalRemote(t, "acme", "widget")
|
||||
|
||||
// archied side: real Store, a capturing Forge, and the Manager that
|
||||
// actually holds the (unused-for-file-remotes) push token.
|
||||
st := store.OpenTest(t)
|
||||
if _, err := st.EnqueueIssue(ctx, "acme", "widget", 1, "feat: bootstrap test", "", "bootstrap", ""); err != nil {
|
||||
t.Fatalf("enqueue: %v", err)
|
||||
}
|
||||
task, err := st.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("claim: (%v, %v)", task, err)
|
||||
}
|
||||
|
||||
fg := &prCapturingForge{}
|
||||
daemonTrees := &worktree.Manager{
|
||||
WorkDir: t.TempDir(),
|
||||
Token: "unused-for-file-remotes",
|
||||
BotUser: "archie-bot",
|
||||
BotEmail: "archie-bot@example.com",
|
||||
BaseURL: "file://" + host,
|
||||
}
|
||||
|
||||
// The daemon always prepares the worktree before container acquire --
|
||||
// reproduce that here so the container's bind mount has real content.
|
||||
hostDir, _, err := daemonTrees.Prepare(ctx, "acme", "widget", "main", 1, task.Title, "", "bootstrap")
|
||||
if err != nil {
|
||||
t.Fatalf("daemon-side prepare: %v", err)
|
||||
}
|
||||
|
||||
srv := startEmbeddedForTaskRun(t)
|
||||
url := srv.ClientURL()
|
||||
serverConn := connectForTaskRun(t, url)
|
||||
|
||||
unsubStore, err := (&storerpc.Server{Store: st, Log: slog.New(slog.DiscardHandler)}).Register(serverConn)
|
||||
if err != nil {
|
||||
t.Fatalf("register storerpc: %v", err)
|
||||
}
|
||||
t.Cleanup(unsubStore)
|
||||
unsubForge, err := (&forgerpc.Server{Forge: fg, Log: slog.New(slog.DiscardHandler)}).Register(serverConn)
|
||||
if err != nil {
|
||||
t.Fatalf("register forgerpc: %v", err)
|
||||
}
|
||||
t.Cleanup(unsubForge)
|
||||
unsubTrees, err := (&worktreerpc.Server{Trees: daemonTrees, Log: slog.New(slog.DiscardHandler)}).Register(serverConn)
|
||||
if err != nil {
|
||||
t.Fatalf("register worktreerpc: %v", err)
|
||||
}
|
||||
t.Cleanup(unsubTrees)
|
||||
|
||||
// archie-agent side: its own NATS connection, "bind mount" is just
|
||||
// hostDir since this test runs in a single process/filesystem.
|
||||
agentConn := connectForTaskRun(t, url)
|
||||
|
||||
req := taskrun.Request{
|
||||
Task: task,
|
||||
Repo: config.Repo{Owner: "acme", Name: "widget", Base: "main"},
|
||||
Cfg: config.Config{}.ForTask(),
|
||||
}
|
||||
|
||||
fakeRunner := agentexec.RunnerFactory(func(map[string]agentexec.Provider, *slog.Logger) agentexec.Runner {
|
||||
return panicRunner{t}
|
||||
})
|
||||
|
||||
resp, err := runTask(ctx, req, agentConn, fakeRunner, hostDir, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatalf("runTask: %v", err)
|
||||
}
|
||||
if resp.Status != store.StatusPROpen {
|
||||
t.Fatalf("resp.Status = %q, want %q (task: %+v)", resp.Status, store.StatusPROpen, resp.Task)
|
||||
}
|
||||
if len(fg.prs) != 1 {
|
||||
t.Fatalf("expected 1 CreatePR call, got %d: %+v", len(fg.prs), fg.prs)
|
||||
}
|
||||
|
||||
// The authoritative state landed in archied's store via storerpc, not
|
||||
// just in the in-memory tc.Task.
|
||||
stored, err := st.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
if err != nil || stored == nil {
|
||||
t.Fatalf("TaskByIssue: (%+v, %v)", stored, err)
|
||||
}
|
||||
if stored.Status != store.StatusPROpen {
|
||||
t.Fatalf("stored task status = %q, want %q", stored.Status, store.StatusPROpen)
|
||||
}
|
||||
if stored.PRNumber != 5 {
|
||||
t.Fatalf("stored task PR number = %d, want 5", stored.PRNumber)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(filepath.Join(hostDir, ".archie", "bootstrap.md")); err != nil {
|
||||
t.Fatalf("expected bootstrap marker file: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user