feat(workflow): plugin-registered step vocabulary resolved identically on both sides

Resolves archie-core-fwmp. The workflow step vocabulary is owned by an
injected workflow.Manager (internal/domain/workflow), assembled from a single
compiled-in provider set (internal/infrastructure/workflowsteps) and registered
at each composition root, following ARCHITECTURE.md#plugin-engine-rule-strict
invariant 2 and the memory family's house pattern. Replaces the five hardcoded
BuiltinStepRegistry() call sites.
This commit is contained in:
sam committed 2026-09-21 20:29:36 +10:00
commit 34c8602dc1
19 files changed
+1671 -48

No files matched your search

@@ -0,0 +1,89 @@
package agentworker
import (
"slices"
"testing"
"gopkg.in/yaml.v3"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
)
// stepVocabularyProbe is a provider set of one, used only to prove the
// manager a root builds is live: registering through it must reach its
// vocabulary.
type stepVocabularyProbe struct{}
func (stepVocabularyProbe) Name() string { return "probe" }
func (stepVocabularyProbe) StepTypes() []workflow.StepType {
return []workflow.StepType{{Name: "probe.registered", Factory: func(yaml.Node) (workflow.Stage, error) {
return workflow.Stage{Name: "probe.registered"}, nil
}}}
}
// TestProductionWorkerDependenciesRegisterTheSharedStepVocabulary pins the
// executing side's composition root. productionWorkerDependencies is reached
// only by Run, so nothing else fails if it stops registering the shared
// provider set (internal/infrastructure/workflowsteps) and hands the worker a
// manager with no shipped stage: every compile then fails at run time, in a
// container, per task.
func TestProductionWorkerDependenciesRegisterTheSharedStepVocabulary(t *testing.T) {
dependencies, err := productionWorkerDependencies()
if err != nil {
t.Fatalf("productionWorkerDependencies: %v", err)
}
requireSharedStepVocabulary(t, dependencies.steps)
}
// requireSharedStepVocabulary holds a composition root's manager to both halves
// of the contract: it resolves the shipped vocabulary, and it is live enough to
// take a provider registered through it.
func requireSharedStepVocabulary(t *testing.T, steps *workflow.Manager) {
t.Helper()
if steps == nil {
t.Fatal("the composition root registered no workflow step vocabulary")
}
got := steps.StepTypes()
// Containment, not equality: adding a provider to the shared set
// (workflowsteps.Providers) is the documented way a step type arrives, and
// that must not have to edit this guard. What it holds is that the shipped
// stages are all present, which is what a root regressing to
// workflow.NewManager() loses.
for name := range workflow.BuiltinStepRegistry() {
if !slices.Contains(got, name) {
t.Errorf("the composition root resolves %v, which is missing the shipped stage %q", got, name)
}
}
// The other half is provenance: every name the root resolves must be
// declared by the shared provider set, not by a near-identical provider of
// the root's own, because that set is what ties this process's vocabulary to
// the State Store that validates against it. It is content, not identity --
// the shipped provider rebuilds its factories on every call.
declared := sharedStepTypeNames()
for _, name := range got {
if !slices.Contains(declared, name) {
t.Errorf("the composition root resolves %q, which no provider in the shared set declares", name)
}
}
if err := steps.Register(stepVocabularyProbe{}); err != nil {
t.Fatalf("register a provider through the root's manager: %v", err)
}
if _, resolved := steps.Registry()["probe.registered"]; !resolved {
t.Fatal("a provider registered through the root's manager did not reach its vocabulary")
}
}
// sharedStepTypeNames returns the step types the shared provider set declares,
// read through the same Providers() seam the composition roots register.
func sharedStepTypeNames() []string {
names := make([]string, 0)
for _, provider := range workflowsteps.Providers() {
for _, stepType := range provider.StepTypes() {
names = append(names, stepType.Name)
}
}
slices.Sort(names)
return names
}
+31 -7
View File
@@ -176,6 +176,11 @@ type taskDependencies struct {
store workflow.Store
trees remoteTrees
events agentexec.EventPublisher
// steps is the workflow step vocabulary pinned definitions are compiled
// against, registered at the composition root and injected: this is the
// executing half of the contract whose validating half is the control
// plane's (archie-core-fwmp).
steps *workflow.Manager
}
type runnerFactory func(map[string]agentexec.Provider, *slog.Logger) agentexec.Runner
@@ -212,7 +217,7 @@ func routeTask(req taskrun.Request, registry workflow.Registry) workflow.Workflo
// runs it, and reports its terminal outcome.
// Store remains archied's authority; Response.Task is a logging snapshot.
func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependencies, newRunner runnerFactory, workDir string, log *slog.Logger) (*taskrun.Response, error) {
wf, err := resolvePinnedWorkflow(&req)
wf, err := CompilePinnedWorkflow(&req, dependencies.steps)
if err != nil {
return nil, err
}
@@ -311,18 +316,37 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen
}, nil
}
func resolvePinnedWorkflow(req *taskrun.Request) (workflow.Workflow, error) {
// CompilePinnedWorkflow resolves and compiles the immutable definition the task
// request carries, against this process's step vocabulary. Production execution
// and the workflow step-vocabulary contract test
// (internal/app/controlplane/step_vocabulary_agreement_test.go) both enter
// through it.
//
// A request that carries no definition is routed and pinned from the shipped
// definitions, which writes the resolved workflow name, YAML, and digest back
// onto req and req.Task: the run's TaskContext carries that task record, so the
// pin has to land on the request the caller handed in.
func CompilePinnedWorkflow(req *taskrun.Request, steps *workflow.Manager) (workflow.Workflow, error) {
// steps is this process's required step vocabulary, so a nil one is a wiring
// mistake at the composition root (productionWorkerDependencies) rather than
// a runtime condition: name it instead of dereferencing it.
if steps == nil {
return workflow.Workflow{}, errors.New("compile pinned workflow: no step vocabulary: the composition root must register the provider set (infrastructure/workflowsteps.NewManager) before the first compile")
}
// One resolution for the whole function: both compiles below read the
// vocabulary the composition root registered, never the builtin registry.
vocabulary := steps.Registry()
if req.WorkflowDefinition == "" {
shipped := workflow.ShippedDefinitions()
registry := make(workflow.Registry, len(shipped.Definitions))
routing := make(workflow.Registry, len(shipped.Definitions))
for _, definition := range shipped.Definitions {
compiled, compileErr := workflow.ParseAndCompile(definition.YAML, workflow.BuiltinStepRegistry())
compiled, compileErr := workflow.ParseAndCompile(definition.YAML, vocabulary)
if compileErr != nil {
return workflow.Workflow{}, fmt.Errorf("compile shipped workflow definition: %w", compileErr)
}
registry[definition.ID] = compiled
routing[definition.ID] = compiled
}
selected := routeTask(*req, registry)
selected := routeTask(*req, routing)
req.Task.Workflow = selected.Name
entry, ok := shipped.DefinitionByID(selected.Name)
if !ok {
@@ -332,7 +356,7 @@ func resolvePinnedWorkflow(req *taskrun.Request) (workflow.Workflow, error) {
req.Task.WorkflowDefinitionYAML = entry.YAML
req.Task.WorkflowDefinitionDigest = workflow.DigestDefinition(entry.YAML)
}
wf, err := workflow.ParseAndCompile(req.WorkflowDefinition, workflow.BuiltinStepRegistry())
wf, err := workflow.ParseAndCompile(req.WorkflowDefinition, vocabulary)
if err != nil {
return workflow.Workflow{}, fmt.Errorf("compile pinned workflow definition: %w", err)
}
@@ -31,6 +31,7 @@ import (
"github.com/samcharles93/archie-core/internal/forgerpc"
agentnats "github.com/samcharles93/archie-core/internal/infrastructure/agenttransport/nats"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
"github.com/samcharles93/archie-core/internal/installtype"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/taskrun"
@@ -38,6 +39,18 @@ import (
"github.com/samcharles93/archie-core/internal/worktreerpc"
)
// testSteps builds the production workflow step vocabulary for tests that are
// not about the vocabulary itself (the composition-level agreement test in
// internal/app/controlplane is).
func testSteps(t *testing.T) *workflow.Manager {
t.Helper()
steps, err := workflowsteps.NewManager()
if err != nil {
t.Fatalf("build workflow step vocabulary: %v", err)
}
return steps
}
// ── regression: archie-core#520 -- worktree ownership must be
// reconciled before push, since the agent commits as root inside the
// container and the daemon reads those same loose objects as its own
@@ -399,7 +412,7 @@ func TestRunTaskExecutesBootstrapWorkflowEndToEnd(t *testing.T) {
Cfg: config.Config{BotUser: "archie-bot", BotEmail: "archie-bot@example.com"}.ForTask(),
}
fakeRunner := runnerFactory(func(map[string]agentexec.Provider, *slog.Logger) agentexec.Runner { return panicRunner{t} })
response, err := runTask(ctx, req, taskDependencies{forge: fg, store: st, trees: remote}, fakeRunner, hostDir, slog.New(slog.DiscardHandler))
response, err := runTask(ctx, req, taskDependencies{forge: fg, store: st, trees: remote, steps: testSteps(t)}, fakeRunner, hostDir, slog.New(slog.DiscardHandler))
if err != nil {
t.Fatalf("runTask: %v", err)
}
@@ -531,7 +544,7 @@ func TestRunTaskRestoresWorktreeOwnershipOnEveryExit(t *testing.T) {
_, err := runTask(t.Context(), taskrun.Request{
Task: &workflow.Task{ID: 77, Branch: "feat/77-probe", Workflow: "implement"},
Repo: config.Repo{Owner: "acme", Name: "widget", Base: "main"},
}, taskDependencies{}, runnerFactory(func(map[string]agentexec.Provider, *slog.Logger) agentexec.Runner {
}, taskDependencies{steps: testSteps(t)}, runnerFactory(func(map[string]agentexec.Provider, *slog.Logger) agentexec.Runner {
return nil
}), workDir, slog.New(slog.DiscardHandler))
if err == nil {
@@ -632,7 +645,7 @@ func TestExecuteTaskRequestUsesInfrastructureRPCDependencies(t *testing.T) {
Cfg: config.Config{}.ForTask(),
WorktreeGrant: grant,
}
response, err := executeTaskRequest(ctx, request, transport, hostDir, slog.New(slog.DiscardHandler))
response, err := executeTaskRequest(ctx, request, transport, hostDir, slog.New(slog.DiscardHandler), testSteps(t))
if err != nil {
t.Fatal(err)
}
@@ -750,7 +763,7 @@ func TestExecuteTaskRequestForwardsWorkflowEventsOverNATS(t *testing.T) {
Cfg: config.Config{}.ForTask(),
WorktreeGrant: grant,
}
response, err := executeTaskRequest(ctx, request, transport, hostDir, slog.New(slog.DiscardHandler))
response, err := executeTaskRequest(ctx, request, transport, hostDir, slog.New(slog.DiscardHandler), testSteps(t))
if err != nil {
t.Fatal(err)
}
+26 -5
View File
@@ -11,6 +11,7 @@ import (
"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"
)
@@ -57,9 +58,23 @@ type workerDependencies struct {
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
}
func productionWorkerDependencies() workerDependencies {
// 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)
@@ -70,13 +85,18 @@ func productionWorkerDependencies() workerDependencies {
<-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 {
return run(ctx, settings, log, productionWorkerDependencies())
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 {
@@ -112,7 +132,7 @@ func run(ctx context.Context, settings Settings, log *slog.Logger, dependencies
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)
return executeTaskRequest(ctx, request, transport, workDir, log, dependencies.steps)
}, log)
if err != nil {
log.Error("taskrun subscribe failed", "err", err)
@@ -136,13 +156,14 @@ type taskServiceTransport interface {
EventPublisher() agentexec.EventPublisher
}
func executeTaskRequest(ctx context.Context, request taskrun.Request, transport taskServiceTransport, workDir string, log *slog.Logger) (*taskrun.Response, error) {
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 {
+20 -2
View File
@@ -27,6 +27,7 @@ import (
"github.com/samcharles93/archie-core/internal/app/controlplane"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/container"
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/daemon"
"github.com/samcharles93/archie-core/internal/domain/applystatus"
"github.com/samcharles93/archie-core/internal/domain/curator"
@@ -116,6 +117,15 @@ type boot struct {
stateStoreGrants *staterpc.GrantIssuer
stateStoreToken string
controlPlane *controlplane.Client
// controlPlaneRPC is the State Store's control-plane transport, kept so the
// daemon root can build its workflow-definitions client from it
// (openDaemonWorkflowDefinitions). The gateway root never builds that client:
// it resolves no workflow step type.
controlPlaneRPC controlpb.ControlPlaneServiceClient
// workflowDefinitions is the one control-plane surface that resolves
// workflow step types. It is separate from controlPlane because it is the
// only surface that needs the process's step vocabulary.
workflowDefinitions *controlplane.WorkflowDefinitionsClient
// executionSettings is the last workflow execution settings the control
// plane published. They arrive on a watch rather than in the file
// document, so reloadConfig re-applies them from here.
@@ -357,7 +367,15 @@ func (b *boot) openStateStoreAdapter() error {
return err
}
b.stateStore = client
b.controlPlane = controlplane.NewRPCClient(client.ControlPlane())
// The daemon reads workflow definitions through the workflow-definitions
// client, built by the daemon root (openDaemonWorkflowDefinitions) on this
// process's step vocabulary, so the daemon resolves the same vocabulary the
// State Store server validates against. It is not built here because the
// gateway root shares this adapter and resolves no step type. That agreement
// holds within one build: the State Store is a separate binary, and a skewed
// deploy is only fixed by a matching deploy.
b.controlPlaneRPC = client.ControlPlane()
b.controlPlane = controlplane.NewRPCClient(b.controlPlaneRPC)
b.applyStatus = applystatus.New(b.processName, client, b.log)
b.stateStoreGrants = &staterpc.GrantIssuer{Client: client}
b.stateStoreToken = b.cfg.Services.ResolvedToken(config.ServiceNameState, b.secrets.Getenv)
@@ -1242,7 +1260,7 @@ func (b *boot) buildDaemon() {
AgentStatus: b.agentStatus,
KindWorkflows: b.kindWorkflows,
LabelWorkflows: b.labelWorkflows,
WorkflowDefinitions: b.controlPlane,
WorkflowDefinitions: b.workflowDefinitions,
}
if identities, ok := b.stateStore.(identity.Repository); ok {
b.d.IdentityRepository = identities
+12 -7
View File
@@ -370,13 +370,18 @@ func Run() int { //nolint:cyclop,funlen // the composition root's setup sequence
if err := b.openStores(ctx); err != nil {
return 1
}
// Resolve the State Store contract adapter as the remote *staterpc.Client
// dialed to [services.state].target; the daemon no longer owns archie.db
// in-process, so an empty target is a composition error
// (docs/prds/state-store-contract.md §12 step 7). This runs after
// openStores has resolved b.secrets and before setupObservability wires the
// dashboard's storage surfaces (§10).
if err := b.openStateStoreAdapter(); err != nil {
// Resolve the State Store surfaces before setupObservability wires the
// dashboard's storage surfaces (§10): the shared contract adapter (the
// remote *staterpc.Client dialed to [services.state].target; the daemon no
// longer owns archie.db in-process, so an empty target is a composition
// error, docs/prds/state-store-contract.md §12 step 7) and then, daemon
// root only, the workflow-definitions client on this process's step
// vocabulary. The daemon resolves step types through that client, so it is
// built here -- after the adapter, whose transport it wraps -- and before
// buildDaemon captures it. The gateway root shares only the adapter and
// resolves no step type, so openDaemonStateSurfaces owns the order and
// step_vocabulary_test.go pins the cut.
if err := b.openDaemonStateSurfaces(); err != nil {
return 1
}
if err := b.loadRuntimeConfig(ctx); err != nil {
+29 -1
View File
@@ -100,7 +100,12 @@ func RunStateStore(ctx context.Context, options StateStoreOptions) error {
if !ok {
return fmt.Errorf("state store does not support control-plane resources")
}
control := controlplane.NewServer(resources)
// The validating side's control plane, built here at the composition root
// before the first definition is read or replaced.
control, err := openStateStoreControlPlane(resources)
if err != nil {
return err
}
versions, err := control.ImportConfig(ctx, b.cfg)
if err != nil {
return fmt.Errorf("import control-plane resources: %w", err)
@@ -137,6 +142,29 @@ func RunStateStore(ctx context.Context, options StateStoreOptions) error {
return serveStateStore(ctx, listener, deps, opts)
}
// openStateStoreControlPlane builds the State Store's control plane server: the
// validating side of the workflow step vocabulary, registered here at the
// composition root before the first definition is read or replaced. The same
// provider set (internal/infrastructure/workflowsteps) is what archie-agent
// registers before it compiles one, so within one build a definition this
// server admits is compilable there; a skewed deploy is only fixed by a
// matching deploy.
//
// It is separate from RunStateStore so that function stays within its
// complexity budget, and step_vocabulary_test.go pins both the call to
// stepVocabulary below and RunStateStore's call to this function.
func openStateStoreControlPlane(resources controlplane.ResourceStore) (*controlplane.Server, error) {
steps, err := stepVocabulary()
if err != nil {
return nil, fmt.Errorf("register workflow step vocabulary: %w", err)
}
server, err := controlplane.NewServer(resources, steps)
if err != nil {
return nil, fmt.Errorf("build control plane server: %w", err)
}
return server, nil
}
func migrateLegacySchedules(ctx context.Context, control *controlplane.Server, dbPath string, version int64) error {
if version != 1 {
return nil
+82
View File
@@ -0,0 +1,82 @@
package archied
import (
"fmt"
"github.com/samcharles93/archie-core/internal/app/controlplane"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
)
// stepVocabulary builds the workflow step vocabulary a process resolves
// workflow definitions against: the shared provider set
// (internal/infrastructure/workflowsteps), registered at the composition root,
// before the first resolution.
//
// Two roots call it, and both are roots that resolve a step type: RunStateStore
// (the State Store's validating side) and openDaemonWorkflowDefinitions (the
// daemon's workflow-definitions client). A root that cannot reach a workflow
// definition registers no vocabulary and cannot be failed by one, which is why
// the gateway root and internal/app/archiemessaging are not here.
//
// It is a named function so that step_vocabulary_test.go can fail if a root
// stops resolving the shipped stages, or hands a constructor a manager other
// than the one this returns; the roots themselves own a SQLite file and dial
// gRPC, so the test asserts their wiring by parsing their bodies.
//
// Agreement is within one build: the State Store and archie-agent are
// separately deployed binaries, so a State Store built from newer source than
// the agent it dispatches to can still disagree, and only a matching deploy
// fixes that.
func stepVocabulary() (*workflow.Manager, error) { return workflowsteps.NewManager() }
// openDaemonWorkflowDefinitions builds the daemon's workflow-definitions
// client on the process step vocabulary, and is called by the daemon root alone
// (main.go's Run) before buildDaemon captures the client.
//
// It is deliberately not part of openStateStoreAdapter, which the gateway root
// shares: the gateway reads catalog, runtime settings and personas, never a
// workflow definition, so registering a vocabulary there would be the dead
// vocabulary this shape removed from internal/app/archiemessaging -- a root that
// cannot consume it must not be failed by it.
//
// The daemon reads definitions through it; no production process replaces
// definitions yet (see controlplane.WorkflowDefinitionsClient.
// ReplaceWorkflowDefinitions).
func (b *boot) openDaemonWorkflowDefinitions() error {
steps, err := stepVocabulary()
if err != nil {
return fmt.Errorf("register workflow step vocabulary: %w", err)
}
definitions, err := controlplane.NewWorkflowDefinitionsClient(b.controlPlaneRPC, steps)
if err != nil {
return fmt.Errorf("build workflow definitions client: %w", err)
}
b.workflowDefinitions = definitions
return nil
}
// openDaemonStateSurfaces opens the daemon's State Store surfaces in one step:
// the adapter shared with every other root (openStateStoreAdapter) and, on top
// of it, the daemon-only workflow-definitions client
// (openDaemonWorkflowDefinitions).
//
// It exists because the daemon root is a flat composition sequence with no
// complexity budget left to spend on a second adjacent guard, and the order the
// two calls owe each other is a property of the pair, not of that sequence: the
// definitions client wraps the control-plane transport the adapter dials, so it
// cannot be built first, and buildDaemon captures the client, so it cannot be
// built later. step_vocabulary_test.go pins exactly that order here.
//
// The gateway root calls openStateStoreAdapter directly and stops there; the
// daemon-only half stays out of that function for the reason above it.
func (b *boot) openDaemonStateSurfaces() error {
if err := b.openStateStoreAdapter(); err != nil {
return err
}
if err := b.openDaemonWorkflowDefinitions(); err != nil {
b.log.Error("workflow definitions client", "err", err)
return err
}
return nil
}
@@ -0,0 +1,270 @@
package archied
import (
"go/ast"
"go/parser"
"go/token"
"slices"
"testing"
"gopkg.in/yaml.v3"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
)
// stepVocabularyProbe is a provider set of one, used only to prove the manager
// a root builds is live: registering through it must reach its vocabulary.
type stepVocabularyProbe struct{}
func (stepVocabularyProbe) Name() string { return "probe" }
func (stepVocabularyProbe) StepTypes() []workflow.StepType {
return []workflow.StepType{{Name: "probe.registered", Factory: func(yaml.Node) (workflow.Stage, error) {
return workflow.Stage{Name: "probe.registered"}, nil
}}}
}
// sharedStepTypeNames returns the step types the shared provider set
// (internal/infrastructure/workflowsteps) declares. It is read through the same
// Providers() seam the composition roots register, rather than from
// workflow.BuiltinStepRegistry(): the shipped stages arrive by registration, and
// a provider added to that set is the documented way a step type enters every
// binary at once.
func sharedStepTypeNames() []string {
names := make([]string, 0)
for _, provider := range workflowsteps.Providers() {
for _, stepType := range provider.StepTypes() {
names = append(names, stepType.Name)
}
}
slices.Sort(names)
return names
}
// requireSharedStepVocabulary holds a composition root's manager to both halves
// of the contract: it resolves the shipped vocabulary, and it is live enough to
// take a provider registered through it.
func requireSharedStepVocabulary(t *testing.T, steps *workflow.Manager) {
t.Helper()
if steps == nil {
t.Fatal("the composition root registered no workflow step vocabulary")
}
got := steps.StepTypes()
// Containment, not equality: adding a provider to the shared set is the
// documented way a step type arrives, and that must not have to edit this
// guard. What the guard holds is that no shipped stage is missing, which is
// what a root regressing to workflow.NewManager() loses.
for name := range workflow.BuiltinStepRegistry() {
if !slices.Contains(got, name) {
t.Errorf("the composition root resolves %v, which is missing the shipped stage %q", got, name)
}
}
// The other half is provenance: every name the root resolves must be
// declared by the shared provider set, not by a near-identical provider of
// the root's own. That set is what ties this process's vocabulary to the
// other side of the contract. It is content, not identity -- the shipped
// provider rebuilds its factories on every call -- so a root that stopped
// importing the shared set and hand-rolled an equal one would still pass.
declared := sharedStepTypeNames()
for _, name := range got {
if !slices.Contains(declared, name) {
t.Errorf("the composition root resolves %q, which no provider in the shared set declares", name)
}
}
if err := steps.Register(stepVocabularyProbe{}); err != nil {
t.Fatalf("register a provider through the root's manager: %v", err)
}
if _, resolved := steps.Registry()["probe.registered"]; !resolved {
t.Fatal("a provider registered through the root's manager did not reach its vocabulary")
}
}
// TestStepVocabularyRegistersTheSharedProviderSet pins the unit the daemon root
// resolves its vocabulary from. Handing this function an empty manager
// (workflow.NewManager) would leave the daemon unable to decode the stored
// definitions it pins onto tasks.
func TestStepVocabularyRegistersTheSharedProviderSet(t *testing.T) {
steps, err := stepVocabulary()
if err != nil {
t.Fatalf("stepVocabulary: %v", err)
}
requireSharedStepVocabulary(t, steps)
}
// TestArchiedRootsResolveTheStepVocabularyFromThatFunction pins both halves of
// each root's wiring: the root reaches the vocabulary through stepVocabulary,
// and the manager it returns is the one handed to the constructor that resolves
// a step type with it. Neither root can be executed in a unit test -- Run owns
// a SQLite file and a listen address, openDaemonWorkflowDefinitions dials the
// State Store -- so both are asserted by source position, the way
// composition_order_test.go pins the memory-engine ordering for the same
// reason. A root that built its own manager, or built one and handed the
// constructor a different one, would resolve a vocabulary without the shipped
// stages.
func TestArchiedRootsResolveTheStepVocabularyFromThatFunction(t *testing.T) {
for _, link := range []struct{ file, function, constructor string }{
// The validating side: the State Store's control plane server.
{"state_store.go", "openStateStoreControlPlane", "NewServer"},
// The executing side's client, built by the daemon root alone.
{"step_vocabulary.go", "openDaemonWorkflowDefinitions", "NewWorkflowDefinitionsClient"},
} {
t.Run(link.function+"->stepVocabulary->"+link.constructor, func(t *testing.T) {
body := parsedBody(t, link.file, link.function)
manager := stepVocabularyAssignment(body)
if manager == "" {
t.Fatalf("%s does not build its step vocabulary through stepVocabulary()", link.function)
}
if !callPassesIdent(body, link.constructor, manager) {
t.Errorf("%s does not hand the manager stepVocabulary() returned (%s) to %s()", link.function, manager, link.constructor)
}
})
}
}
// TestOnlyTheDaemonRootRegistersAStepVocabulary pins the cut the shape applies
// to every other process: a root that cannot resolve a step type registers no
// vocabulary and cannot be failed by one. openStateStoreAdapter is shared by the
// daemon and the gateway, and the gateway resolves no step type -- its
// control-plane surfaces are catalog, runtime settings and personas -- so the
// vocabulary belongs to the daemon root alone, exactly as
// internal/app/archiemessaging's dead vocabulary was removed. Asserted by
// source position for the same reason as above.
func TestOnlyTheDaemonRootRegistersAStepVocabulary(t *testing.T) {
if pos := identCallPosition(parsedBody(t, "bootstrap.go", "openStateStoreAdapter"), "stepVocabulary"); pos != token.NoPos {
t.Error("openStateStoreAdapter registers a step vocabulary; it is shared with the gateway root, which never resolves a step type")
}
if fileMentionsIdent(t, "gateway.go", "stepVocabulary") {
t.Error("the gateway root file mentions stepVocabulary; the gateway resolves no workflow step type")
}
// The daemon root opens both halves -- the shared adapter and the
// daemon-only definitions client -- through one call, so the sequence costs
// Run a single branch. The guarantee is the one this pin always held,
// relocated to where the sequence now lives: adapter first, then the client
// built on its transport, both before buildDaemon captures the client.
run := parsedBody(t, "main.go", "Run")
surfaces := methodCallPosition(run, "openDaemonStateSurfaces")
build := methodCallPosition(run, "buildDaemon")
if surfaces == token.NoPos {
t.Fatal("Run never opens the daemon's State Store surfaces; every task pin would fall back to the shipped definitions")
}
if build == token.NoPos || surfaces > build {
t.Errorf("Run opens the daemon's State Store surfaces at %v, after buildDaemon at %v: the daemon would capture no definitions surface", surfaces, build)
}
// Neither half may also be opened from Run directly: a second call site
// would be a copy of the sequence outside the order asserted below.
for _, direct := range []string{"openStateStoreAdapter", "openDaemonWorkflowDefinitions"} {
if pos := methodCallPosition(run, direct); pos != token.NoPos {
t.Errorf("Run calls %s directly at %v; the daemon's State Store surfaces open through openDaemonStateSurfaces alone", direct, pos)
}
}
sequence := parsedBody(t, "step_vocabulary.go", "openDaemonStateSurfaces")
adapter := methodCallPosition(sequence, "openStateStoreAdapter")
wiring := methodCallPosition(sequence, "openDaemonWorkflowDefinitions")
if wiring == token.NoPos {
t.Fatal("openDaemonStateSurfaces never builds the daemon's workflow-definitions client; every task pin would fall back to the shipped definitions")
}
if adapter == token.NoPos || wiring < adapter {
t.Errorf("openDaemonStateSurfaces builds the workflow-definitions client at %v, at or before openStateStoreAdapter at %v: it would wrap the transport the adapter has not opened yet", wiring, adapter)
}
}
func parsedBody(t *testing.T, file, function string) *ast.BlockStmt {
t.Helper()
parsed, err := parser.ParseFile(token.NewFileSet(), file, nil, 0)
if err != nil {
t.Fatal(err)
}
return methodBody(t, parsed, function)
}
// stepVocabularyAssignment returns the identifier assigned from a direct call
// to stepVocabulary() in body, or "" when body never calls it.
func stepVocabularyAssignment(body *ast.BlockStmt) string {
manager := ""
ast.Inspect(body, func(node ast.Node) bool {
assign, ok := node.(*ast.AssignStmt)
if !ok || len(assign.Lhs) == 0 || len(assign.Rhs) == 0 || manager != "" {
return true
}
call, ok := assign.Rhs[0].(*ast.CallExpr)
if !ok {
return true
}
callee, ok := call.Fun.(*ast.Ident)
if !ok || callee.Name != "stepVocabulary" {
return true
}
if lhs, ok := assign.Lhs[0].(*ast.Ident); ok {
manager = lhs.Name
}
return true
})
return manager
}
// callPassesIdent reports whether some call to name (bare or selected) passes an
// identifier called ident as an argument.
func callPassesIdent(body *ast.BlockStmt, name, ident string) bool {
found := false
ast.Inspect(body, func(node ast.Node) bool {
call, ok := node.(*ast.CallExpr)
if !ok || !callNameIs(call, name) {
return true
}
for _, argument := range call.Args {
if passed, ok := argument.(*ast.Ident); ok && passed.Name == ident {
found = true
}
}
return true
})
return found
}
func callNameIs(call *ast.CallExpr, name string) bool {
switch fun := call.Fun.(type) {
case *ast.Ident:
return fun.Name == name
case *ast.SelectorExpr:
return fun.Sel.Name == name
}
return false
}
// fileMentionsIdent reports whether any declaration in file names ident.
func fileMentionsIdent(t *testing.T, file, ident string) bool {
t.Helper()
parsed, err := parser.ParseFile(token.NewFileSet(), file, nil, 0)
if err != nil {
t.Fatal(err)
}
mentions := false
ast.Inspect(parsed, func(node ast.Node) bool {
if found, ok := node.(*ast.Ident); ok && found.Name == ident {
mentions = true
}
return true
})
return mentions
}
// identCallPosition returns the position of the first call to a bare function
// name in body, or token.NoPos when the body never calls it.
func identCallPosition(body *ast.BlockStmt, name string) token.Pos {
position := token.NoPos
ast.Inspect(body, func(node ast.Node) bool {
call, ok := node.(*ast.CallExpr)
if !ok {
return true
}
ident, ok := call.Fun.(*ast.Ident)
if ok && ident.Name == name && position == token.NoPos {
position = call.Pos()
}
return true
})
return position
}
+33 -4
View File
@@ -17,6 +17,12 @@ import (
"github.com/samcharles93/archie-core/internal/infrastructure/cronstore"
)
// Client is the control-plane client for every resource that does not resolve
// a workflow step type: catalog, history, settings, personas, schedules. It
// carries no step vocabulary, so a process that never reads or writes a
// workflow definition -- archie-messaging, which only loads channel settings,
// and archie-gateway, which reads catalog, runtime settings and personas --
// needs no provider set and cannot be failed by one.
type Client struct{ rpc pb.ControlPlaneServiceClient }
func NewClient(conn grpc.ClientConnInterface) *Client {
@@ -25,6 +31,25 @@ func NewClient(conn grpc.ClientConnInterface) *Client {
func NewRPCClient(client pb.ControlPlaneServiceClient) *Client { return &Client{rpc: client} }
// WorkflowDefinitionsClient reads and replaces the workflow-definitions
// resource, the one control-plane surface whose stored values name workflow
// step types. Resolving those names needs the step vocabulary the process
// registered at its composition root, so the vocabulary is a constructor
// dependency of this surface and of no other: a caller that cannot reach
// workflow definitions cannot ask for one.
type WorkflowDefinitionsClient struct {
rpc pb.ControlPlaneServiceClient
steps workflow.StepRegistry
}
func NewWorkflowDefinitionsClient(client pb.ControlPlaneServiceClient, steps *workflow.Manager) (*WorkflowDefinitionsClient, error) {
registry, err := stepRegistry(steps)
if err != nil {
return nil, err
}
return &WorkflowDefinitionsClient{rpc: client, steps: registry}, nil
}
func (c *Client) Catalog(ctx context.Context) ([]*pb.ResourceDescriptor, error) {
response, err := c.rpc.Catalog(ctx, &pb.CatalogRequest{})
if err != nil {
@@ -33,20 +58,24 @@ func (c *Client) Catalog(ctx context.Context) ([]*pb.ResourceDescriptor, error)
return response.Resources, nil
}
func (c *Client) WorkflowDefinitions(ctx context.Context) (workflow.WorkflowDefinitionCollection, int64, error) {
func (c *WorkflowDefinitionsClient) WorkflowDefinitions(ctx context.Context) (workflow.WorkflowDefinitionCollection, int64, error) {
response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: WorkflowDefinitionsKind})
if err != nil {
return workflow.WorkflowDefinitionCollection{}, 0, clientError(err)
}
definitions, err := workflow.DecodeDefinitionCollection(response.Resource.ValueJson, workflow.BuiltinStepRegistry())
definitions, err := workflow.DecodeDefinitionCollection(response.Resource.ValueJson, c.steps)
return definitions, response.Resource.Version, err
}
// ReplaceWorkflowDefinitions replaces the collection. Passing
// workflow.ShippedDefinitions() restores all shipped definitions while keeping
// the previous override in resource history.
func (c *Client) ReplaceWorkflowDefinitions(ctx context.Context, definitions workflow.WorkflowDefinitionCollection, expectedVersion int64, actor, source, requestID string) (int64, error) {
value, err := encodeWorkflowDefinitions(definitions)
//
// No production process calls it today: the daemon's only consumer of this
// surface reads (internal/daemon's WorkflowDefinitions interface), so this half
// is reached by tests until a writer exists.
func (c *WorkflowDefinitionsClient) ReplaceWorkflowDefinitions(ctx context.Context, definitions workflow.WorkflowDefinitionCollection, expectedVersion int64, actor, source, requestID string) (int64, error) {
value, err := encodeWorkflowDefinitions(definitions, c.steps)
if err != nil {
return 0, err
}
+12 -3
View File
@@ -11,6 +11,7 @@ import (
"google.golang.org/protobuf/types/known/timestamppb"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/store"
)
@@ -41,13 +42,21 @@ type Server struct {
ordered []Definition
}
func NewServer(resources ResourceStore) *Server {
definitions := builtinDefinitions()
// NewServer builds the control plane server the State Store serves. steps is
// the workflow step vocabulary the composition root registered; this is the
// validating side of the vocabulary archie-agent executes against in a
// matching build (see stepRegistry: a skewed deploy can still disagree).
func NewServer(resources ResourceStore, steps *workflow.Manager) (*Server, error) {
registry, err := stepRegistry(steps)
if err != nil {
return nil, err
}
definitions := builtinDefinitions(registry)
byKind := make(map[string]Definition, len(definitions))
for _, definition := range definitions {
byKind[definition.Kind] = definition
}
return &Server{store: resources, definitions: byKind, ordered: definitions}
return &Server{store: resources, definitions: byKind, ordered: definitions}, nil
}
func (s *Server) Catalog(context.Context, *pb.CatalogRequest) (*pb.CatalogResponse, error) {
+33 -8
View File
@@ -13,15 +13,40 @@ import (
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/agent"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
"github.com/samcharles93/archie-core/internal/store"
)
// testSteps builds the production workflow step vocabulary for tests that are
// not about the vocabulary itself; step_vocabulary_agreement_test.go is the one
// that registers a provider and drives every production resolution site.
func testSteps(t *testing.T) *workflow.Manager {
t.Helper()
steps, err := workflowsteps.NewManager()
if err != nil {
t.Fatalf("build workflow step vocabulary: %v", err)
}
return steps
}
// testServer builds the State Store's control plane against the production
// vocabulary, so a test that is not about the vocabulary still exercises the
// constructor production uses.
func testServer(t *testing.T, resources ResourceStore) *Server {
t.Helper()
server, err := NewServer(resources, testSteps(t))
if err != nil {
t.Fatalf("build control plane server: %v", err)
}
return server
}
func TestCatalogCarriesShippedWorkflowDefinitionsForRestore(t *testing.T) {
t.Parallel()
resources := store.OpenTest(t)
defer resources.Close()
catalog, err := NewServer(resources).Catalog(t.Context(), &pb.CatalogRequest{})
catalog, err := testServer(t, resources).Catalog(t.Context(), &pb.CatalogRequest{})
if err != nil {
t.Fatal(err)
}
@@ -48,7 +73,7 @@ func TestImportConfigSeedsWorkflowDefinitionsWithoutOverwritingOverride(t *testi
resources := store.OpenTest(t)
defer resources.Close()
server := NewServer(resources)
server := testServer(t, resources)
if _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
t.Fatal(err)
}
@@ -64,7 +89,7 @@ func TestImportConfigSeedsWorkflowDefinitionsWithoutOverwritingOverride(t *testi
t.Fatal("seeded definitions omit remediate")
}
custom := workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "custom", YAML: "id: custom\nsteps:\n - type: bootstrap.apply\n"}}}
value, err := encodeWorkflowDefinitions(custom)
value, err := encodeWorkflowDefinitions(custom, testSteps(t).Registry())
if err != nil {
t.Fatal(err)
}
@@ -88,7 +113,7 @@ func TestImportConfigSeedsPersonasWithoutOverwritingEdits(t *testing.T) {
resources := store.OpenTest(t)
defer resources.Close()
server := NewServer(resources)
server := testServer(t, resources)
if _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
t.Fatal(err)
}
@@ -126,7 +151,7 @@ func TestImportWorkflowExecutionSettingsDoesNotOverwriteExistingValue(t *testing
resources := store.OpenTest(t)
defer resources.Close()
server := NewServer(resources)
server := testServer(t, resources)
first := workflow.ExecutionSettings{MaxModelToolSteps: 10, MaxRuntime: time.Minute, MaxConsecutiveGateFailures: 2}
if _, err := server.ImportWorkflowExecutionSettings(t.Context(), first); err != nil {
t.Fatal(err)
@@ -152,7 +177,7 @@ func TestRegistryRoutesAndValidatesDefinitions(t *testing.T) {
resources := store.OpenTest(t)
defer resources.Close()
server := NewServer(resources)
server := testServer(t, resources)
if _, err := server.ImportConfig(t.Context(), config.Config{Containers: config.ContainerConfig{PullPolicy: "missing"}}); err != nil {
t.Fatal(err)
}
@@ -182,7 +207,7 @@ func TestProviderSeedKeepsReferencesAndNeverResolvedSecrets(t *testing.T) {
resources := store.OpenTest(t)
defer resources.Close()
server := NewServer(resources)
server := testServer(t, resources)
cfg := config.Config{Providers: map[string]config.Provider{"openai": {Class: "openai", APIKeyEnv: "OPENAI_API_KEY", APIKey: config.SecretRef{Engine: "env", Key: "OPENAI_API_KEY"}}}}
if _, err := server.ImportConfig(context.Background(), cfg); err != nil {
t.Fatal(err)
@@ -209,7 +234,7 @@ func TestHistoryCarriesEveryRevisionWithItsAudit(t *testing.T) {
resources := store.OpenTest(t)
defer resources.Close()
server := NewServer(resources)
server := testServer(t, resources)
if _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
t.Fatal(err)
}
+6 -3
View File
@@ -1,14 +1,17 @@
package controlplane
import pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
import (
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
const (
objectSchema = `{"type":"object"}`
arraySchema = `{"type":"array"}`
)
func builtinDefinitions() []Definition {
definitions := []Definition{workflowDefinition(), workflowDefinitionsDefinition(), personaDefinition(), scheduleDefinition()}
func builtinDefinitions(steps workflow.StepRegistry) []Definition {
definitions := []Definition{workflowDefinition(), workflowDefinitionsDefinition(steps), personaDefinition(), scheduleDefinition()}
definitions = append(definitions, modelDefinitions()...)
definitions = append(definitions, operationalDefinitions()...)
return definitions
@@ -0,0 +1,397 @@
// The workflow step vocabulary is a contract between processes: the validating
// side (the State Store's control plane) admits a definition and the executing
// side (archie-agent) compiles it. Two packages that each pass their own tests
// and disagree with each other is the failure archie-core-fwmp exists to
// prevent, so this is the one test that registers a provider through the
// production Manager and drives the production entry points that resolve a step
// type with it: the State Store server, the daemon's workflow-definitions
// client (its read path, and its write path, which no production caller reaches
// yet) and agentworker.CompilePinnedWorkflow. A site these do not enumerate is
// caught by TestNoProductionSiteReachesForTheBuiltinStepRegistry below.
//
// "Agreement" here means within one build: archie-state-store and archie-agent
// are separately deployed binaries, so a State Store built from newer source
// than the agent it dispatches to can still disagree, and only a matching
// deploy fixes that. This file cannot reach across a deploy boundary and does
// not claim to.
package controlplane
import (
"context"
"encoding/json"
"go/ast"
"go/parser"
"go/token"
"io/fs"
"path/filepath"
"strings"
"testing"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"gopkg.in/yaml.v3"
"github.com/samcharles93/archie-core/internal/app/agentworker"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/taskrun"
)
const (
probeWorkflow = "probe"
// probeStepType is contributed by the provider this test registers through
// the production Manager, so no shared registry can hand it to one side and
// not the others.
probeStepType = "probe.registered"
// unregisteredStepType is declared by no provider, so every side must
// refuse it.
unregisteredStepType = "probe.unregistered"
)
// probeProvider is a plugin set of one: a step type no shipped workflow
// registers, whose stage names itself so a side that merely failed to error
// cannot pass.
type probeProvider struct{}
func (probeProvider) Name() string { return "probe" }
func (probeProvider) StepTypes() []workflow.StepType {
return []workflow.StepType{{Name: probeStepType, Factory: func(yaml.Node) (workflow.Stage, error) {
return workflow.Stage{Name: probeStepType}, nil
}}}
}
// probeSteps builds the process vocabulary the way a composition root does —
// through the production constructor — and registers the probe provider on top
// of it.
func probeSteps(t *testing.T) *workflow.Manager {
t.Helper()
steps, err := workflowsteps.NewManager()
if err != nil {
t.Fatalf("build workflow step vocabulary: %v", err)
}
if err := steps.Register(probeProvider{}); err != nil {
t.Fatalf("register the probe provider through the production Manager: %v", err)
}
return steps
}
func probeDefinition(stepType string) string {
return "id: " + probeWorkflow + "\nsteps:\n - type: " + stepType + "\n"
}
func probeCollection(stepType string) workflow.WorkflowDefinitionCollection {
return workflow.WorkflowDefinitionCollection{
Definitions: []workflow.WorkflowDefinitionEntry{{ID: probeWorkflow, YAML: probeDefinition(stepType)}},
}
}
// TestEveryProductionResolutionSiteResolvesTheRegisteredStepType drives the
// State Store server, the control-plane client's read and write paths, and
// archie-agent with one vocabulary: a site that resolves the builtin registry
// instead of the manager fails its own assertion, because the probe step type
// exists nowhere else.
func TestEveryProductionResolutionSiteResolvesTheRegisteredStepType(t *testing.T) {
tests := []struct {
name string
stepType string
admitted bool
// wantStage is the stage a definition must compile to. It is empty for
// a shipped stage, whose factory keeps the workflow-local stage name.
wantStage string
}{
{name: "step type registered through the manager", stepType: probeStepType, admitted: true, wantStage: probeStepType},
{name: "shipped stage", stepType: "bootstrap.apply", admitted: true},
{name: "step type no provider declares", stepType: unregisteredStepType},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
steps := probeSteps(t)
// Every side asserts against the same expectation, so a side that
// resolves a vocabulary other than the registered one fails its own
// subtest. That shared column is the agreement this file pins.
t.Run("state store server", func(t *testing.T) {
before, after, err := admitThroughStateStore(t, steps, test.stepType)
if !test.admitted {
if code := status.Code(err); code != codes.InvalidArgument {
t.Fatalf("State Store answered %v (code %s), want InvalidArgument: a refused definition is a validation failure, not a store failure", err, code)
}
requireRefusal(t, "the State Store server", test.stepType, err)
return
}
requireAdmission(t, "the State Store server", test.stepType, err)
if after != before+1 {
t.Errorf("store version moved %d -> %d, want exactly one write: a repeated request ID is replayed idempotently and would make this admission vacuous", before, after)
}
})
t.Run("workflow-definitions client", func(t *testing.T) {
value, err := json.Marshal(probeCollection(test.stepType))
if err != nil {
t.Fatalf("encode definitions: %v", err)
}
rpc := &definitionsClient{value: value}
client, err := NewWorkflowDefinitionsClient(rpc, steps)
if err != nil {
t.Fatalf("build workflow-definitions client: %v", err)
}
// Read path: the daemon decodes the stored collection here.
collection, _, readErr := client.WorkflowDefinitions(t.Context())
// Write path: the client re-validates before it sends anything.
_, writeErr := client.ReplaceWorkflowDefinitions(t.Context(), probeCollection(test.stepType), 4, "test", "test", "replace:"+test.stepType)
if !test.admitted {
requireRefusal(t, "the control-plane client read", test.stepType, readErr)
requireRefusal(t, "the control-plane client write", test.stepType, writeErr)
if rpc.command != nil {
t.Errorf("the client sent %q for a step type it does not resolve", rpc.command.ValueJson)
}
return
}
requireAdmission(t, "the control-plane client read", test.stepType, readErr)
if _, ok := collection.DefinitionByID(probeWorkflow); !ok {
t.Errorf("client read %#v, want the stored %q definition", collection.Definitions, probeWorkflow)
}
requireAdmission(t, "the control-plane client write", test.stepType, writeErr)
if rpc.command == nil {
t.Fatal("the client accepted the collection without sending a command")
}
if !strings.Contains(string(rpc.command.ValueJson), test.stepType) {
t.Errorf("the client sent %q, which does not carry step type %q", rpc.command.ValueJson, test.stepType)
}
})
t.Run("archie-agent", func(t *testing.T) {
compiled, err := agentworker.CompilePinnedWorkflow(probeRequest(test.stepType), steps)
if !test.admitted {
requireRefusal(t, "archie-agent", test.stepType, err)
return
}
requireAdmission(t, "archie-agent", test.stepType, err)
if compiled.Name != probeWorkflow || len(compiled.Stages) != 1 {
t.Fatalf("compiled workflow = %+v, want the single-stage %q definition", compiled, probeWorkflow)
}
if test.wantStage != "" && compiled.Stages[0].Name != test.wantStage {
t.Errorf("compiled stage = %q, want the provider's own stage %q", compiled.Stages[0].Name, test.wantStage)
}
})
})
}
}
// TestNilStepVocabularyFailsClosedAtEveryResolutionSite pins the guard on the
// manager every resolution site now requires. A nil manager is a wiring bug at
// the composition root, so each site must name it and refuse to resolve, rather
// than dereference it: a nil-pointer panic is the same failure with no clue in
// it.
func TestNilStepVocabularyFailsClosedAtEveryResolutionSite(t *testing.T) {
resources := store.OpenTest(t)
t.Cleanup(func() {
if err := resources.Close(); err != nil {
t.Errorf("close test store: %v", err)
}
})
if _, err := NewServer(resources, nil); err == nil || !strings.Contains(err.Error(), "no workflow step vocabulary") {
t.Errorf("NewServer with no step vocabulary: error = %v, want the missing-vocabulary refusal", err)
}
if _, err := NewWorkflowDefinitionsClient(&definitionsClient{}, nil); err == nil || !strings.Contains(err.Error(), "no workflow step vocabulary") {
t.Errorf("NewWorkflowDefinitionsClient with no step vocabulary: error = %v, want the missing-vocabulary refusal", err)
}
if _, err := agentworker.CompilePinnedWorkflow(probeRequest(probeStepType), nil); err == nil || !strings.Contains(err.Error(), "no step vocabulary") {
t.Errorf("CompilePinnedWorkflow with no step vocabulary: error = %v, want the missing-vocabulary refusal", err)
}
}
// TestAgentWorkerCompilesShippedDefinitionsFromTheInjectedVocabulary pins the
// shipped-definition route inside CompilePinnedWorkflow. That route compiles
// definitions whose steps are all shipped stages, so no plugin assertion can
// reach it; a vocabulary that carries the probe step type and nothing else must
// fail there, and it cannot fail if the route reaches for the builtin registry
// instead of the manager the composition root registered.
func TestAgentWorkerCompilesShippedDefinitionsFromTheInjectedVocabulary(t *testing.T) {
steps := workflow.NewManager()
if err := steps.Register(probeProvider{}); err != nil {
t.Fatalf("register the probe provider through the production Manager: %v", err)
}
_, err := agentworker.CompilePinnedWorkflow(&taskrun.Request{Task: &workflow.Task{ID: 1}}, steps)
if err == nil {
t.Fatal("the shipped-definition route compiled against a vocabulary carrying no shipped stage")
}
if !strings.Contains(err.Error(), "compile shipped workflow definition") || !strings.Contains(err.Error(), "bootstrap.") {
t.Errorf("error = %v, want the shipped stage the injected vocabulary could not resolve", err)
}
}
func requireAdmission(t *testing.T, side, stepType string, err error) {
t.Helper()
if err != nil {
t.Fatalf("%s refused step type %q: %v", side, stepType, err)
}
}
// requireRefusal checks the error is a refusal *of this step type*: a store
// outage, a transport failure or an unrelated compile error must not be able to
// stand in for one.
func requireRefusal(t *testing.T, side, stepType string, err error) {
t.Helper()
if err == nil {
t.Fatalf("%s accepted step type %q, which no provider declares", side, stepType)
}
if !strings.Contains(err.Error(), stepType) {
t.Errorf("%s failed for %q with %v, which does not name the step type: that is not a refusal of it", side, stepType, err)
}
}
// admitThroughStateStore writes one definition the way an operator does: a
// replace command against the workflow-definitions resource of a server built
// by the production constructor.
func admitThroughStateStore(t *testing.T, steps *workflow.Manager, stepType string) (before, after int64, err error) {
t.Helper()
resources := store.OpenTest(t)
t.Cleanup(func() {
if closeErr := resources.Close(); closeErr != nil {
t.Errorf("close test store: %v", closeErr)
}
})
server, err := NewServer(resources, steps)
if err != nil {
t.Fatalf("build control plane server: %v", err)
}
if resource, resourceErr := resources.Resource(t.Context(), WorkflowDefinitionsKind); resourceErr == nil {
before = resource.Version
}
value, err := json.Marshal(probeCollection(stepType))
if err != nil {
t.Fatalf("encode definitions: %v", err)
}
written, err := server.Command(t.Context(), &pb.CommandRequest{
Kind: WorkflowDefinitionsKind, Command: "replace", ValueJson: value,
ExpectedVersion: before, Actor: "test", Source: "test",
// A request ID per step type: the store replays a repeated one
// idempotently, and a replayed write would validate nothing.
RequestId: "admit:" + stepType,
})
if err != nil {
return before, before, err
}
return before, written.Resource.Version, nil
}
func probeRequest(stepType string) *taskrun.Request {
definition := probeDefinition(stepType)
return &taskrun.Request{
Task: &workflow.Task{
ID: 1,
Workflow: probeWorkflow,
WorkflowDefinitionDigest: workflow.DigestDefinition(definition),
},
WorkflowDefinition: definition,
}
}
// definitionsClient answers the control-plane RPCs the definitions client uses,
// so the production client path is driven without a live State Store.
type definitionsClient struct {
value []byte
command *pb.CommandRequest
}
func (c *definitionsClient) Catalog(context.Context, *pb.CatalogRequest, ...grpc.CallOption) (*pb.CatalogResponse, error) {
panic("Catalog is not part of the workflow-definitions path")
}
func (c *definitionsClient) Query(context.Context, *pb.QueryRequest, ...grpc.CallOption) (*pb.QueryResponse, error) {
return &pb.QueryResponse{Resource: &pb.Resource{
Kind: WorkflowDefinitionsKind, Version: 4, ValueJson: c.value,
}}, nil
}
func (c *definitionsClient) History(context.Context, *pb.HistoryRequest, ...grpc.CallOption) (*pb.HistoryResponse, error) {
panic("History is not part of the workflow-definitions path")
}
func (c *definitionsClient) Command(_ context.Context, request *pb.CommandRequest, _ ...grpc.CallOption) (*pb.CommandResponse, error) {
c.command = request
return &pb.CommandResponse{Resource: &pb.Resource{Version: 5}}, nil
}
func (c *definitionsClient) Watch(context.Context, *pb.WatchRequest, ...grpc.CallOption) (grpc.ServerStreamingClient[pb.WatchResponse], error) {
panic("Watch is not part of the workflow-definitions path")
}
// TestNoProductionSiteReachesForTheBuiltinStepRegistry guards the class of
// defect archie-core-fwmp exists to remove: a call site that resolves workflow
// step types out of workflow.BuiltinStepRegistry() instead of the manager its
// composition root registered. The agreement test above can only drive the
// entry points it enumerates, so a sixth one added later would validate, or
// fail to compile, against a vocabulary no other process has. Exactly two
// non-test files may name it: the domain file that declares it, and the shipped
// provider that bundles the shipped stages through it.
func TestNoProductionSiteReachesForTheBuiltinStepRegistry(t *testing.T) {
allowed := map[string]string{
filepath.Join("internal", "domain", "workflow", "definition.go"): "declares BuiltinStepRegistry",
filepath.Join("internal", "infrastructure", "workflowsteps", "workflowsteps.go"): "bundles the shipped stages as a provider",
}
// The module root, three levels up from this package.
root := filepath.Join("..", "..", "..")
scanned := 0
walkErr := filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
name := entry.Name()
if entry.IsDir() {
// The root is "../../..", whose own name starts with a dot: only
// directories below it are filtered.
if path == root {
return nil
}
// tools is a separate module, and the rest carry no Archie source.
if name == "tools" || name == "node_modules" || name == "testdata" || name == "vendor" || strings.HasPrefix(name, ".") {
return fs.SkipDir
}
return nil
}
if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
return nil
}
relative, relErr := filepath.Rel(root, path)
if relErr != nil {
return relErr
}
if _, permitted := allowed[relative]; permitted {
return nil
}
file, parseErr := parser.ParseFile(token.NewFileSet(), path, nil, 0)
if parseErr != nil {
return parseErr
}
scanned++
ast.Inspect(file, func(node ast.Node) bool {
if ident, ok := node.(*ast.Ident); ok && ident.Name == "BuiltinStepRegistry" {
t.Errorf("%s names BuiltinStepRegistry; only %s (%s) and %s (%s) may, or that resolution site keeps a step vocabulary of its own",
relative,
filepath.Join("internal", "domain", "workflow", "definition.go"), allowed[filepath.Join("internal", "domain", "workflow", "definition.go")],
filepath.Join("internal", "infrastructure", "workflowsteps", "workflowsteps.go"), allowed[filepath.Join("internal", "infrastructure", "workflowsteps", "workflowsteps.go")])
}
return true
})
return nil
})
if walkErr != nil {
t.Fatalf("scan the module for BuiltinStepRegistry: %v", walkErr)
}
if scanned == 0 {
t.Fatal("the scan read no non-test Go file; it is not looking at the module")
}
}
@@ -2,6 +2,7 @@ package controlplane
import (
"encoding/json"
"errors"
"fmt"
"github.com/samcharles93/archie-core/internal/config"
@@ -10,7 +11,23 @@ import (
const WorkflowDefinitionsKind = "workflow-definitions"
func workflowDefinitionsDefinition() Definition {
// stepRegistry is this package's single resolution site for the workflow step
// vocabulary, and the guard on the manager it must be handed. The manager is
// built at the composition root (infrastructure/workflowsteps.NewManager) and
// injected, so the State Store server -- the validating side -- and the
// workflow-definitions client both resolve the vocabulary that composition
// root registered. Agreement is within one build: the State Store and
// archie-agent are separately deployed binaries, so a State Store built from
// newer source than the agent it dispatches to can still disagree, and only a
// matching deploy fixes that.
func stepRegistry(steps *workflow.Manager) (workflow.StepRegistry, error) {
if steps == nil {
return nil, errors.New("control plane: no workflow step vocabulary: the composition root must register the provider set (infrastructure/workflowsteps.NewManager) before the first resolution")
}
return steps.Registry(), nil
}
func workflowDefinitionsDefinition(steps workflow.StepRegistry) Definition {
return Definition{
Kind: WorkflowDefinitionsKind,
Title: "Workflow definitions",
@@ -23,14 +40,14 @@ func workflowDefinitionsDefinition() Definition {
return workflow.ShippedDefinitions()
},
Validate: func(input []byte) error {
_, err := workflow.DecodeDefinitionCollection(input, workflow.BuiltinStepRegistry())
_, err := workflow.DecodeDefinitionCollection(input, steps)
return err
},
}
}
func encodeWorkflowDefinitions(collection workflow.WorkflowDefinitionCollection) ([]byte, error) {
if err := workflow.ValidateDefinitionCollection(collection, workflow.BuiltinStepRegistry()); err != nil {
func encodeWorkflowDefinitions(collection workflow.WorkflowDefinitionCollection, steps workflow.StepRegistry) ([]byte, error) {
if err := workflow.ValidateDefinitionCollection(collection, steps); err != nil {
return nil, fmt.Errorf("%w: %w", ErrValidation, err)
}
return json.Marshal(collection)
+168
View File
@@ -0,0 +1,168 @@
package workflow
import (
"errors"
"fmt"
"maps"
"reflect"
"regexp"
"slices"
"sync"
)
// stepTypeIdentifier is the shape a provider name and a step type name must
// have: a lowercase, dotted identifier, so a contributed step type cannot
// smuggle whitespace or case into the vocabulary two processes compare, and so
// one step type has exactly one spelling. It reserves nothing: a contribution
// that spells a shipped stage's name is well formed, and what refuses it is
// Register's claimed-name check, not this rule.
var stepTypeIdentifier = regexp.MustCompile(`^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$`)
// StepType is one named workflow step type: the vocabulary word a YAML
// workflow names, plus the factory that builds its stage.
type StepType struct {
Name string
Factory StepFactory
}
// StepTypeProvider is the typed extension point through which a plugin
// contributes workflow step types. StepTypes is the capability-specific
// operation — a provider exposing identity metadata alone would be a metadata
// entry, not a step-type provider — and it is the only method the family calls.
type StepTypeProvider interface {
// Name identifies the provider in registration diagnostics.
Name() string
// StepTypes returns every step type this provider contributes. The
// manager validates the whole contribution before applying any of it.
StepTypes() []StepType
}
// Manager is the workflow step-type family owner: it controls registration,
// validation, and resolution of the vocabulary that workflow definitions are
// parsed and compiled against.
//
// It is a constructed, injected value. There is deliberately no package-level
// registry and no init()-time registration: each process builds a Manager at
// its composition root from the same provider set
// (internal/infrastructure/workflowsteps) and injects it, so within one build
// a definition that validates on the validating side is compilable on the
// executing side. That agreement is per build: the State Store and archie-agent
// are separately deployed binaries, so one built from newer source than the
// other can still disagree, and only a matching deploy fixes that.
//
// Registration is expected to finish before the first resolution, and that
// order is a documented constraint rather than an enforced one: Registry hands
// back a copy, so a Register that arrives after a consumer resolved is not
// observed by that consumer. Register every provider before injecting the
// manager.
type Manager struct {
mu sync.Mutex
registry StepRegistry
// owners names the provider that claimed each step type, so a collision is
// reported against the provider that is already there rather than as an
// anonymous duplicate. The stages of the shipped workflows are claimed by
// the provider that contributes them, which is how a contribution that
// shadows a shipped stage is refused.
owners map[string]string
providers []string
}
// NewManager builds an empty family manager. It holds no vocabulary of its own:
// the shipped stages are a provider like any other, registered by the process's
// composition root, so the vocabulary every side resolves is the one that was
// actually registered.
func NewManager() *Manager {
return &Manager{registry: StepRegistry{}, owners: map[string]string{}}
}
// Register validates one provider's contribution and applies it. Every way a
// contribution can be invalid is refused here, at the producer: a nil or
// unnamed provider, a malformed provider or step-type identifier, a step type
// with no factory, a step type another provider already claimed (including one
// that shadows a shipped stage), and a provider declaring one type twice.
//
// Validation is atomic: the whole contribution is checked before any of it is
// applied, so a refused provider contributes nothing.
func (m *Manager) Register(provider StepTypeProvider) error {
if isNilProvider(provider) {
return errors.New("workflow step type provider is nil")
}
name := provider.Name()
if !stepTypeIdentifier.MatchString(name) {
return fmt.Errorf("workflow step type provider name %q is not a stable identifier", name)
}
contributed := provider.StepTypes()
pending := make(StepRegistry, len(contributed))
order := make([]string, 0, len(contributed))
for _, stepType := range contributed {
switch {
case !stepTypeIdentifier.MatchString(stepType.Name):
return fmt.Errorf("workflow step type provider %q: step type %q is not a stable identifier", name, stepType.Name)
case stepType.Factory == nil:
return fmt.Errorf("workflow step type provider %q: step type %q has no factory", name, stepType.Name)
}
if _, declared := pending[stepType.Name]; declared {
return fmt.Errorf("workflow step type provider %q declares step type %q twice", name, stepType.Name)
}
pending[stepType.Name] = stepType.Factory
order = append(order, stepType.Name)
}
m.mu.Lock()
defer m.mu.Unlock()
for _, stepType := range order {
if owner, claimed := m.owners[stepType]; claimed {
return fmt.Errorf("workflow step type %q is already claimed by provider %q", stepType, owner)
}
}
for _, stepType := range order {
m.registry[stepType] = pending[stepType]
m.owners[stepType] = name
}
m.providers = append(m.providers, name)
return nil
}
// Registry returns the assembled vocabulary for the parser and compiler entry
// points. It is a copy: the closed set is a property of the manager, not
// something a consumer can widen.
func (m *Manager) Registry() StepRegistry {
m.mu.Lock()
defer m.mu.Unlock()
registry := make(StepRegistry, len(m.registry))
maps.Copy(registry, m.registry)
return registry
}
// StepTypes returns every registered step type name, sorted.
func (m *Manager) StepTypes() []string {
registry := m.Registry()
names := make([]string, 0, len(registry))
for name := range registry {
names = append(names, name)
}
slices.Sort(names)
return names
}
// Providers returns the registered provider names, sorted.
func (m *Manager) Providers() []string {
m.mu.Lock()
defer m.mu.Unlock()
return slices.Sorted(slices.Values(m.providers))
}
// isNilProvider catches a nil interface and a typed nil pointer alike: a
// provider cannot answer Name() in either case, so it is refused rather than
// dereferenced. Mirrors internal/domain/memory's engine check.
func isNilProvider(provider StepTypeProvider) bool {
value := reflect.ValueOf(provider)
switch value.Kind() {
case reflect.Invalid:
return true
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
return value.IsNil()
}
return false
}
+217
View File
@@ -0,0 +1,217 @@
package workflow
import (
"slices"
"strings"
"testing"
"gopkg.in/yaml.v3"
)
// namedFactory builds a stage that names itself, so a test can tell which step
// type a definition compiled from.
func namedFactory(name string) StepFactory {
return func(yaml.Node) (Stage, error) { return Stage{Name: name}, nil }
}
// testProvider is a provider set of one, for driving the manager directly.
type testProvider struct {
name string
types []StepType
}
func (p testProvider) Name() string { return p.name }
func (p testProvider) StepTypes() []StepType { return p.types }
func provider(name string, names ...string) testProvider {
types := make([]StepType, 0, len(names))
for _, stepType := range names {
types = append(types, StepType{Name: stepType, Factory: namedFactory(stepType)})
}
return testProvider{name: name, types: types}
}
// shippedProvider is the provider that contributes the stages of the shipped
// workflows, which is where a bundled step type arrives from in production.
func shippedProvider() testProvider {
registry := BuiltinStepRegistry()
names := make([]string, 0, len(registry))
for name := range registry {
names = append(names, name)
}
return provider("shipped", names...)
}
// TestManagerRefusesInvalidContributions is the family's validation contract:
// every way a contribution can be wrong is refused at registration, and a
// refused contribution applies nothing.
func TestManagerRefusesInvalidContributions(t *testing.T) {
t.Parallel()
tests := []struct {
name string
before []StepTypeProvider
provider StepTypeProvider
want string
}{
{
name: "nil provider",
want: "is nil",
},
{
name: "unnamed provider",
provider: provider(""),
want: "not a stable identifier",
},
{
name: "malformed provider name",
provider: provider("Probe Plugin", "probe.one"),
want: "not a stable identifier",
},
{
name: "malformed step type name",
provider: provider("probe", "Probe One"),
want: "not a stable identifier",
},
{
name: "step type with no factory",
provider: testProvider{name: "probe", types: []StepType{{Name: "probe.one"}}},
want: "has no factory",
},
{
name: "provider declaring one type twice",
provider: testProvider{name: "probe", types: []StepType{
{Name: "probe.one", Factory: namedFactory("probe.one")},
{Name: "probe.one", Factory: namedFactory("probe.one")},
}},
want: "twice",
},
{
name: "duplicate claim",
before: []StepTypeProvider{provider("alpha", "alpha.one")},
provider: provider("beta", "alpha.one"),
want: `already claimed by provider "alpha"`,
},
{
name: "shadows a shipped stage",
before: []StepTypeProvider{shippedProvider()},
provider: provider("probe", "bootstrap.apply"),
want: `already claimed by provider "shipped"`,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
manager := NewManager()
for _, before := range test.before {
if err := manager.Register(before); err != nil {
t.Fatalf("setup registration: %v", err)
}
}
before := manager.StepTypes()
err := manager.Register(test.provider)
if err == nil || !strings.Contains(err.Error(), test.want) {
t.Fatalf("Register() error = %v, want containing %q", err, test.want)
}
if after := manager.StepTypes(); !slices.Equal(after, before) {
t.Errorf("a refused contribution changed the vocabulary: %v -> %v", before, after)
}
})
}
}
// TestManagerRefusalAppliesNoneOfAMultiStepContribution pins atomicity: a
// contribution whose first step type is valid and whose second is not leaves
// the vocabulary untouched.
func TestManagerRefusalAppliesNoneOfAMultiStepContribution(t *testing.T) {
t.Parallel()
manager := NewManager()
err := manager.Register(testProvider{name: "probe", types: []StepType{
{Name: "probe.one", Factory: namedFactory("probe.one")},
{Name: "probe.two"},
}})
if err == nil || !strings.Contains(err.Error(), "has no factory") {
t.Fatalf("Register() error = %v, want containing %q", err, "has no factory")
}
if got := manager.StepTypes(); len(got) != 0 {
t.Errorf("vocabulary = %v, want empty: a refused contribution applies nothing", got)
}
if _, resolved := manager.Registry()["probe.one"]; resolved {
t.Error("the valid half of a refused contribution was applied")
}
}
// TestManagerAssemblesTheRegisteredVocabulary is the family's resolution
// contract: what was registered is exactly what workflows can name.
func TestManagerAssemblesTheRegisteredVocabulary(t *testing.T) {
t.Parallel()
manager := NewManager()
for _, contributor := range []StepTypeProvider{
provider("beta", "beta.one", "beta.two"),
shippedProvider(),
provider("alpha", "alpha.one"),
} {
if err := manager.Register(contributor); err != nil {
t.Fatalf("Register(%s): %v", contributor.Name(), err)
}
}
got := manager.StepTypes()
want := make([]string, 0, len(BuiltinStepRegistry())+3)
for name := range BuiltinStepRegistry() {
want = append(want, name)
}
want = append(want, "alpha.one", "beta.one", "beta.two")
slices.Sort(want)
if !slices.Equal(got, want) {
t.Errorf("StepTypes() = %v, want %v", got, want)
}
if providers := manager.Providers(); !slices.Equal(providers, []string{"alpha", "beta", "shipped"}) {
t.Errorf("Providers() = %v, want [alpha beta shipped]", providers)
}
compiled, err := ParseAndCompile("id: probe\nsteps:\n - type: alpha.one\n - type: beta.two\n", manager.Registry())
if err != nil {
t.Fatalf("compile a definition naming contributed step types: %v", err)
}
if compiled.Name != "probe" || len(compiled.Stages) != 2 {
t.Fatalf("compiled = %+v, want the two-stage probe workflow", compiled)
}
if compiled.Stages[0].Name != "alpha.one" || compiled.Stages[1].Name != "beta.two" {
t.Errorf("compiled stages = %q, %q, want the contributing factories' stages",
compiled.Stages[0].Name, compiled.Stages[1].Name)
}
if _, err := ParseAndCompile("id: probe\nsteps:\n - type: unregistered\n", manager.Registry()); err == nil {
t.Error("a step type no provider contributed compiled")
}
}
// TestManagerRegistryIsAClosedSet pins that the assembled vocabulary is a
// property of the manager, not a map a consumer can widen.
func TestManagerRegistryIsAClosedSet(t *testing.T) {
t.Parallel()
manager := NewManager()
if err := manager.Register(provider("alpha", "alpha.one")); err != nil {
t.Fatalf("Register: %v", err)
}
registry := manager.Registry()
registry["smuggled"] = namedFactory("smuggled")
delete(registry, "alpha.one")
if _, ok := manager.Registry()["smuggled"]; ok {
t.Error("a consumer's write reached the manager's vocabulary")
}
if _, ok := manager.Registry()["alpha.one"]; !ok {
t.Error("a consumer's delete removed a registered step type")
}
}
@@ -0,0 +1,72 @@
// Package workflowsteps is the compiled-in workflow step-type provider set:
// the one place a step type is bundled into the Archie binaries that resolve
// one, so no such binary can keep a provider set of its own.
//
// Two composition roots register it, both of them roots that resolve a step
// type: archied's RunStateStore (the State Store's validating side) and
// archied's daemon root (openDaemonWorkflowDefinitions, the executing side's
// workflow-definitions client, alongside agentworker's
// productionWorkerDependencies). Sharing one package is what keeps them
// registering the same vocabulary. Processes that resolve no step type do not
// import it and register nothing: archie-gateway, archie-messaging,
// archie-playbooks and archie-ui.
package workflowsteps
import (
"fmt"
"maps"
"slices"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
// shippedStages is the provider that contributes every stage of the shipped
// workflows (bootstrap, implement, tdd, feasibility, triage, remediate) as a
// workflow step type. It is what makes the shipped vocabulary arrive by
// registration rather than by the manager implying it, so the vocabulary a
// process resolves is always the vocabulary a provider set claimed.
type shippedStages struct{}
func (shippedStages) Name() string { return "shipped" }
func (shippedStages) StepTypes() []workflow.StepType {
registry := workflow.BuiltinStepRegistry()
stepTypes := make([]workflow.StepType, 0, len(registry))
for _, name := range slices.Sorted(maps.Keys(registry)) {
stepTypes = append(stepTypes, workflow.StepType{Name: name, Factory: registry[name]})
}
return stepTypes
}
// Providers returns the provider set the roots that resolve a workflow step
// type register at their composition root, before the first resolution: it is
// what NewManager registers, and what the roots' guards read to hold a
// registered vocabulary to the set it came from. A step type added here becomes
// reachable from the validating side and the executing side at once.
//
// The set is a compiled-in constant rather than a directory scan: a step type
// is a Go factory, and no bridge has been built from the Yaegi-interpreted
// plugins internal/plugin loads to workflow.StepFactory -- those plugins
// satisfy plugin.Plugin's metadata contract only. Such a bridge is possible:
// internal/secret/secretextract wraps an interpreted Engine into the typed
// contract secret.Registry.LoadDir registers (internal/app/archied/
// provider_secrets.go). Until one exists for step types, adding a step type
// means adding a provider here.
func Providers() []workflow.StepTypeProvider {
return []workflow.StepTypeProvider{shippedStages{}}
}
// NewManager builds this process's workflow step-type manager by registering
// the provider set. Every call constructs an independent manager: there is no
// package-level registry and nothing registers at init(), so building the
// vocabulary twice in one process — as `-count=2` does — cannot collide with
// the first build.
func NewManager() (*workflow.Manager, error) {
manager := workflow.NewManager()
for _, provider := range Providers() {
if err := manager.Register(provider); err != nil {
return nil, fmt.Errorf("register workflow step type provider %q: %w", provider.Name(), err)
}
}
return manager, nil
}
@@ -0,0 +1,136 @@
package workflowsteps
import (
"slices"
"strings"
"testing"
"gopkg.in/yaml.v3"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
// TestShippedVocabularyCoversEveryShippedStage is the guard that the bundled
// provider set really carries the shipped stages: a process that registers it
// can compile every shipped workflow, and one that does not has no vocabulary
// at all.
func TestShippedVocabularyCoversEveryShippedStage(t *testing.T) {
t.Parallel()
manager, err := NewManager()
if err != nil {
t.Fatalf("NewManager: %v", err)
}
got := manager.StepTypes()
// Every shipped stage is present...
for name := range workflow.BuiltinStepRegistry() {
if !slices.Contains(got, name) {
t.Errorf("registered vocabulary %v is missing the shipped stage %q", got, name)
}
}
// ...and the vocabulary is exactly what the provider set declares. The
// expectation is derived from Providers() rather than from
// workflow.BuiltinStepRegistry(): adding a provider to this set is the
// documented way a step type arrives, and that must move both sides of this
// assertion together instead of having to edit it.
if want := declaredStepTypes(); !slices.Equal(got, want) {
t.Fatalf("registered vocabulary = %v, want the provider set's declared step types %v", got, want)
}
// The vocabulary arrives by registration, not by implication: a manager
// that was handed no provider set resolves nothing, which is what makes
// every resolution site's use of the injected manager observable.
if got := workflow.NewManager().StepTypes(); len(got) != 0 {
t.Fatalf("an unregistered manager resolves %v, want nothing", got)
}
}
// declaredStepTypes returns every step type the provider set contributes,
// sorted, so a test can hold a manager to the set it was built from.
func declaredStepTypes() []string {
names := make([]string, 0)
for _, provider := range Providers() {
for _, stepType := range provider.StepTypes() {
names = append(names, stepType.Name)
}
}
slices.Sort(names)
return names
}
// TestShippedStagesKeepTheirBehaviourThroughTheManager pins that the provider
// hands the builtin factories through unchanged. The shipped stages are typed,
// non-interpreted steps: each compiles to the stage the builtin registry's own
// factory builds for that step type -- the same name, and Run present or absent
// the same way -- and refuses settings. The one way this enumeration could keep
// every name and lose that guard is to rebuild the factories instead of
// forwarding them, and definition_test.go's assertion cannot see it -- that test
// drives BuiltinStepRegistry directly, which no resolution site does any more:
// production reaches it only inside the shipped provider below.
func TestShippedStagesKeepTheirBehaviourThroughTheManager(t *testing.T) {
t.Parallel()
manager, err := NewManager()
if err != nil {
t.Fatalf("NewManager: %v", err)
}
registry := manager.Registry()
for _, entry := range workflow.ShippedDefinitions().Definitions {
definition, err := workflow.ParseDefinition(entry.YAML, registry)
if err != nil {
t.Fatalf("parse shipped workflow %q through the registered vocabulary: %v", entry.ID, err)
}
compiled, err := workflow.ParseAndCompile(entry.YAML, registry)
if err != nil {
t.Fatalf("compile shipped workflow %q through the registered vocabulary: %v", entry.ID, err)
}
if len(compiled.Stages) != len(definition.Steps) {
t.Fatalf("%s compiled %d stages, want %d", entry.ID, len(compiled.Stages), len(definition.Steps))
}
for i, step := range definition.Steps {
// The expectation is the stage the builtin registry's own factory
// builds for this step type, not a name derived from the step type:
// that is what "the registered factory is the builtin one" means
// for a Stage, which is a name plus an uncomparable func.
shipped, err := workflow.BuiltinStepRegistry()[step.Type](yaml.Node{})
if err != nil {
t.Fatalf("build shipped stage %s: %v", step.Type, err)
}
if compiled.Stages[i].Name != shipped.Name {
t.Errorf("%s step %d (%s) compiled to stage %q, want the shipped stage %q: the registered factory is not the builtin one", entry.ID, i, step.Type, compiled.Stages[i].Name, shipped.Name)
}
if (compiled.Stages[i].Run != nil) != (shipped.Run != nil) {
t.Errorf("%s step %d (%s) compiled to a stage whose Run is present=%t, want the shipped stage's present=%t", entry.ID, i, step.Type, compiled.Stages[i].Run != nil, shipped.Run != nil)
}
}
}
if _, err := workflow.ParseAndCompile("id: probe\nsteps:\n - type: bootstrap.apply\n settings:\n command: rm -rf /\n", registry); err == nil || !strings.Contains(err.Error(), "accepts no settings") {
t.Fatalf("ParseAndCompile() error = %v, want the shipped stage's settings refusal", err)
}
}
// TestNewManagerIsRepeatableWithinOneProcess is the regression guard for
// registering the provider set into shared state: every construction is
// independent, so building the vocabulary twice in one process — as `-count=2`
// does — must succeed and produce the same vocabulary.
func TestNewManagerIsRepeatableWithinOneProcess(t *testing.T) {
t.Parallel()
first, err := NewManager()
if err != nil {
t.Fatalf("first NewManager: %v", err)
}
second, err := NewManager()
if err != nil {
t.Fatalf("second NewManager: %v", err)
}
if !slices.Equal(first.StepTypes(), second.StepTypes()) {
t.Fatalf("two managers resolved different vocabularies: %v and %v", first.StepTypes(), second.StepTypes())
}
if !slices.Equal(first.Providers(), second.Providers()) {
t.Fatalf("two managers registered different providers: %v and %v", first.Providers(), second.Providers())
}
}