Files
archie/internal/app/agentworker/worker.go
T
sam f6037e0d76 fix(agentworker): supply the guardrail engine to every task run
TaskContext.Guardrails was never assigned: the engine was built in
archied's composition root and held on Daemon.Guardrails, which no code
read after workflow execution moved to the full-task worker handoff.
archie-agent is a separate process, so a live engine cannot cross that
handoff. Build the engine at the agentworker composition root (the
process that runs agent stages), thread it through the task dependencies,
and set it on TaskContext; drop the now-dead archied-side construction.

Refs: archie-core-jd5v
2026-10-02 12:37:35 +10:00

188 lines
7.2 KiB
Go

// Package agentworker composes and runs Archie's NATS-connected agent worker.
package agentworker
import (
"context"
"log/slog"
"time"
"github.com/samcharles93/archie-core/internal/agentexec"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/infrastructure/agentboot"
"github.com/samcharles93/archie-core/internal/infrastructure/agentgit"
agentnats "github.com/samcharles93/archie-core/internal/infrastructure/agenttransport/nats"
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
"github.com/samcharles93/archie-core/internal/storage"
"github.com/samcharles93/archie-core/internal/taskrun"
"github.com/samcharles93/archie-core/internal/tools"
)
const rpcTimeout = 60 * time.Second
// StartupError reports which worker startup operation failed. The application
// logs the operation-specific failure once; the command only maps it to exit 1.
type StartupError struct {
Operation string
Err error
}
func (e *StartupError) Error() string { return e.Operation + ": " + e.Err.Error() }
func (e *StartupError) Unwrap() error { return e.Err }
// Settings are process-derived inputs for one worker runtime.
type Settings struct {
NATSURL string
NATSToken string
WorkDir string
// StateStoreTarget and StateStoreToken are the daemon-injected State
// Store gRPC endpoint and bearer token (docs/prds/state-store-contract.md
// §6: STATE_STORE_URL/STATE_STORE_TOKEN, mirroring the NATS_URL/NATS_TOKEN
// handoff). StateStoreTarget is required: the legacy NATS storerpc path
// is deleted (docs/prds/state-store-contract.md §12 step 4).
StateStoreTarget string
StateStoreToken string
}
type workerTransport interface {
Close()
LogPublisher() agentexec.LogPublisher
EventPublisher() agentexec.EventPublisher
SubscribeTasks(context.Context, int64, agentnats.TaskHandler, *slog.Logger) (agentnats.Subscription, error)
Forger(string, time.Duration) workflow.Forger
Store(time.Duration) workflow.Store
Calls(time.Duration) task.Caller
Trees(string, string, time.Duration) agentnats.RemoteTrees
}
type workerDependencies struct {
connect func(context.Context, agentnats.Config, *slog.Logger) (workerTransport, error)
markSafe func(context.Context, string, *slog.Logger) bool
bootID func(string) (int64, error)
wait func(context.Context, *slog.Logger)
// steps is the workflow step vocabulary this process compiles pinned
// definitions against, registered by the composition root before the first
// task is served (infrastructure/workflowsteps is the provider set).
steps *workflow.Manager
// guardrails is the guardrail engine every served task records agent-stage
// outcomes against, built once at this process's composition root.
// archie-agent is the process that runs the stages, so the engine that
// observes them lives here; a live engine cannot cross the task handoff.
guardrails *tools.GuardrailEngine
}
// productionWorkerDependencies builds the worker's process dependencies. The
// workflow step vocabulary is registered here, at the executing side's
// composition root, before the first task is served:
// internal/app/agentworker's step_vocabulary_test.go calls this function and
// fails if it stops using the shared provider set
// (internal/infrastructure/workflowsteps).
func productionWorkerDependencies() (workerDependencies, error) {
steps, err := workflowsteps.NewManager()
if err != nil {
return workerDependencies{}, err
}
return workerDependencies{
connect: func(ctx context.Context, config agentnats.Config, log *slog.Logger) (workerTransport, error) {
return agentnats.Connect(ctx, config, log)
},
markSafe: agentgit.MarkSafe,
bootID: agentboot.TaskID,
wait: func(ctx context.Context, log *slog.Logger) {
<-ctx.Done()
log.Info("archie-agent shutting down")
},
steps: steps,
guardrails: tools.NewGuardrailEngine(tools.DefaultGuardrailConfig()),
}, nil
}
// Run starts the worker, serves full-task requests, and returns after ctx
// cancellation or a startup failure.
func Run(ctx context.Context, settings Settings, log *slog.Logger) error {
dependencies, err := productionWorkerDependencies()
if err != nil {
return &StartupError{Operation: "register workflow step vocabulary", Err: err}
}
return run(ctx, settings, log, dependencies)
}
func run(ctx context.Context, settings Settings, log *slog.Logger, dependencies workerDependencies) error {
if log == nil {
log = slog.New(slog.DiscardHandler)
}
workDir := settings.WorkDir
if workDir == "" {
workDir = storage.WorktreeMountDir
}
dependencies.markSafe(ctx, workDir, log)
transport, err := dependencies.connect(ctx, agentnats.Config{
URL: settings.NATSURL,
Token: settings.NATSToken,
StateStoreURL: settings.StateStoreTarget,
StateStoreToken: settings.StateStoreToken,
}, log)
if err != nil {
operation := "nats connect failed"
log.Error(operation, "err", err)
return &StartupError{Operation: operation, Err: err}
}
defer transport.Close()
taskID, err := dependencies.bootID(workDir)
if err != nil {
log.Error("task boot failed", "err", err)
return &StartupError{Operation: "task boot failed", Err: err}
}
log = slog.New(agentexec.NewSystemLogHandler(log.Handler(), transport.LogPublisher(), taskID))
log.Info("system log publisher attached", "task", taskID)
subscription, err := transport.SubscribeTasks(ctx, taskID, func(ctx context.Context, request taskrun.Request) (*taskrun.Response, error) {
return executeTaskRequest(ctx, request, transport, workDir, log, dependencies.steps, dependencies.guardrails)
}, log)
if err != nil {
log.Error("taskrun subscribe failed", "err", err)
return &StartupError{Operation: "taskrun subscribe failed", Err: err}
}
defer func() {
if err := subscription.Close(); err != nil {
log.Warn("task run unsubscribe failed", "err", err)
}
}()
log.Info("archie-agent ready", "nats", settings.NATSURL)
dependencies.wait(ctx, log)
return nil
}
type taskServiceTransport interface {
Forger(string, time.Duration) workflow.Forger
Store(time.Duration) workflow.Store
Calls(time.Duration) task.Caller
Trees(string, string, time.Duration) agentnats.RemoteTrees
EventPublisher() agentexec.EventPublisher
}
func executeTaskRequest(ctx context.Context, request taskrun.Request, transport taskServiceTransport, workDir string, log *slog.Logger, steps *workflow.Manager, guardrails *tools.GuardrailEngine) (*taskrun.Response, error) {
log.Info("running task", "task", request.Task.ID, "repo", request.Repo.FullName(), "issue", request.Task.IssueNumber)
dependencies := taskDependencies{
forge: transport.Forger(request.Task.Identity, rpcTimeout),
store: transport.Store(rpcTimeout),
calls: transport.Calls(rpcTimeout),
trees: transport.Trees(request.Task.Identity, request.WorktreeGrant, rpcTimeout),
events: transport.EventPublisher(),
steps: steps,
guardrails: guardrails,
}
response, err := runTask(ctx, request, dependencies, newTaskRunner, workDir, log)
if err != nil {
log.Error("task run failed", "task", request.Task.ID, "err", err)
return nil, err
}
log.Info("task run complete", "task", request.Task.ID, "status", response.Status)
return response, nil
}