Files
archie/internal/app/agentworker/worker.go
T
sam 9fb65d0519 fix(workflow): pin the roots, drop the dead vocabulary, guard the nil manager
Third review pass on the step-vocabulary shape, one fix per finding.

P1, roots unpinned. The agreement test built its own manager and injected it, so
it pinned the resolution sites and not the roots that decide the provider set; a
root regressed to workflow.NewManager() (no shipped stages) left go test green.
archied now resolves through one unit, stepVocabulary (step_vocabulary.go), and
agentworker's productionWorkerDependencies is exercised directly:
internal/app/agentworker/step_vocabulary_test.go and
internal/app/archied/step_vocabulary_test.go assert each root's manager resolves
the shared provider set's shipped stages and accepts a provider registered
through it. RunStateStore and openStateStoreAdapter own a SQLite file and a gRPC
dial, so their calls are pinned by source position, the way
composition_order_test.go pins the memory-engine ordering.

P2-B, dead vocabulary. archie-messaging registered a step vocabulary it never
resolved (its only control-plane call is RuntimeChatConfig) and could fail
startup on it before the State Store target guard. The workflow-definitions
surface is now its own type, controlplane.WorkflowDefinitionsClient, so the
vocabulary is a constructor dependency of the one surface that resolves step
types and of nothing else. The messaging root no longer imports workflowsteps.

P2-C, nil manager. A nil *workflow.Manager dereferenced on every resolution path.
stepRegistry and CompilePinnedWorkflow now refuse with an error naming the wiring
mistake; TestNilStepVocabularyFailsClosedAtEveryResolutionSite pins the refusal.

Claim-vs-code corrections: agreement is stated as within one build (vocabulary.go,
stepRegistry, openStateStoreControlPlane, openStateStoreAdapter); the Yaegi claim
now says no bridge to StepFactory has been built and cites
internal/secret/secretextract; the provider set names its three roots;
Manager.Register's ordering is documented as a constraint with its consequence,
and the shape rule no longer claims to reserve shipped stage names; the
shipped-stage test compares against the builtin factory's own stage.
2026-09-21 20:00:37 +10:00

176 lines
6.5 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/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"
)
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
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
}
// 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,
}, 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)
}, 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
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) (*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),
trees: transport.Trees(request.Task.Identity, request.WorktreeGrant, rpcTimeout),
events: transport.EventPublisher(),
steps: steps,
}
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
}