From 54fe3a3331ecb67507f6b20ed9c2e3eff7cdddbc Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 21 Sep 2026 19:42:24 +1000 Subject: [PATCH 1/5] feat(workflow): own the step vocabulary in a family manager registered at each composition root archie-core-fwmp. Every call site hardcoded workflow.BuiltinStepRegistry(), so the step vocabulary a workflow definition may name was closed to the six shipped workflows and archie-agent could compile only what the control plane happened to validate against the same literal. internal/domain/workflow.Manager is the family owner (ARCHITECTURE.md#plugin- engine-rule-strict invariant 2): a constructed, injected value with no package-level registry and no init()-time registration. Register validates at the producer and atomically -- nil or unnamed provider, malformed provider or step-type identifier, a step type with no factory, a duplicate claim, a provider declaring one type twice, and a contribution shadowing a shipped stage are each refused, and a refused contribution applies nothing. Registry() hands back a copy, so the closed set is a property of the manager rather than a convention. internal/infrastructure/workflowsteps is the one package both composition roots import: it holds the compiled-in provider set and builds the manager. archied registers it in RunStateStore (the validating side) and in openStateStoreAdapter (the daemon's client), archie-agent in productionWorkerDependencies (the executing side), and archie-messaging at its own root, each before the first resolution. The five hardcoded sites now resolve the injected manager instead: the State Store's workflow-definitions validate closure and encodeWorkflowDefinitions, the control-plane client's read and write paths, and CompilePinnedWorkflow's shipped -definition and pinned compiles (one resolution per package). step_vocabulary_agreement_test.go registers a provider through the production Manager and drives all three sides with it; breaking any one of the six resolution points back to the builtin registry fails that side's assertion. --- internal/app/agentworker/task_execution.go | 32 +- .../app/agentworker/task_execution_test.go | 21 +- internal/app/agentworker/worker.go | 25 +- internal/app/archied/bootstrap.go | 12 +- .../app/archied/control_plane_reload_test.go | 14 +- internal/app/archied/state_store.go | 12 +- internal/app/archiemessaging/run.go | 10 +- internal/app/controlplane/client.go | 21 +- internal/app/controlplane/controlplane.go | 9 +- .../app/controlplane/controlplane_test.go | 29 +- internal/app/controlplane/definitions.go | 9 +- .../app/controlplane/runtime_config_test.go | 2 +- .../step_vocabulary_agreement_test.go | 291 ++++++++++++++++++ .../app/controlplane/workflow_definitions.go | 16 +- internal/domain/workflow/vocabulary.go | 162 ++++++++++ internal/domain/workflow/vocabulary_test.go | 217 +++++++++++++ .../workflowsteps/workflowsteps.go | 61 ++++ .../workflowsteps/workflowsteps_test.go | 60 ++++ 18 files changed, 958 insertions(+), 45 deletions(-) create mode 100644 internal/app/controlplane/step_vocabulary_agreement_test.go create mode 100644 internal/domain/workflow/vocabulary.go create mode 100644 internal/domain/workflow/vocabulary_test.go create mode 100644 internal/infrastructure/workflowsteps/workflowsteps.go create mode 100644 internal/infrastructure/workflowsteps/workflowsteps_test.go diff --git a/internal/app/agentworker/task_execution.go b/internal/app/agentworker/task_execution.go index d65cbee77..57098fe2f 100644 --- a/internal/app/agentworker/task_execution.go +++ b/internal/app/agentworker/task_execution.go @@ -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,31 @@ 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) { + // 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 +350,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) } diff --git a/internal/app/agentworker/task_execution_test.go b/internal/app/agentworker/task_execution_test.go index 5b0eb7d95..d8f9d3eb8 100644 --- a/internal/app/agentworker/task_execution_test.go +++ b/internal/app/agentworker/task_execution_test.go @@ -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) } diff --git a/internal/app/agentworker/worker.go b/internal/app/agentworker/worker.go index 341651c01..26bcaa779 100644 --- a/internal/app/agentworker/worker.go +++ b/internal/app/agentworker/worker.go @@ -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,17 @@ 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 { +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 +79,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 +126,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 +150,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 { diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 78923a510..7c40b9cc8 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -54,6 +54,7 @@ import ( "github.com/samcharles93/archie-core/internal/infrastructure/skillcurator" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" "github.com/samcharles93/archie-core/internal/infrastructure/taskactions" + "github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps" "github.com/samcharles93/archie-core/internal/logging" "github.com/samcharles93/archie-core/internal/plugin" "github.com/samcharles93/archie-core/internal/plugin/pluginextract" @@ -357,7 +358,16 @@ func (b *boot) openStateStoreAdapter() error { return err } b.stateStore = client - b.controlPlane = controlplane.NewRPCClient(client.ControlPlane()) + // The daemon reads and replaces workflow definitions through the + // control-plane client, so it resolves the same step vocabulary the State + // Store server validates against: registered here, at the composition + // root, before the first read. + steps, err := workflowsteps.NewManager() + if err != nil { + b.log.Error("register workflow step vocabulary", "err", err) + return err + } + b.controlPlane = controlplane.NewRPCClient(client.ControlPlane(), steps) 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) diff --git a/internal/app/archied/control_plane_reload_test.go b/internal/app/archied/control_plane_reload_test.go index 348db1e66..d90785de5 100644 --- a/internal/app/archied/control_plane_reload_test.go +++ b/internal/app/archied/control_plane_reload_test.go @@ -14,8 +14,20 @@ import ( 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/configuration" + "github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps" ) +// reloadSteps builds the production workflow step vocabulary the reload tests' +// control-plane client resolves definitions against. +func reloadSteps(t *testing.T) *workflow.Manager { + t.Helper() + steps, err := workflowsteps.NewManager() + if err != nil { + t.Fatalf("build workflow step vocabulary: %v", err) + } + return steps +} + // controlPlaneStub answers Query from a fixed resource map. queryErr, when // set, fails every Query so a test can drive the unreachable-State-Store // path. @@ -87,7 +99,7 @@ func newReloadBoot(t *testing.T, stub *controlPlaneStub) *boot { b := &boot{ cfg: fileConfig(), log: slog.New(slog.DiscardHandler), - controlPlane: controlplane.NewRPCClient(stub), + controlPlane: controlplane.NewRPCClient(stub, reloadSteps(t)), } b.cfgHolder = config.NewHolder(b.cfg) return b diff --git a/internal/app/archied/state_store.go b/internal/app/archied/state_store.go index f59a26b6e..34c79632e 100644 --- a/internal/app/archied/state_store.go +++ b/internal/app/archied/state_store.go @@ -30,6 +30,7 @@ import ( "github.com/samcharles93/archie-core/internal/infrastructure/cronstore" "github.com/samcharles93/archie-core/internal/infrastructure/readiness" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" + "github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps" "github.com/samcharles93/archie-core/internal/store" ) @@ -100,7 +101,16 @@ 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 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 a definition this + // server admits is compilable there. + steps, err := workflowsteps.NewManager() + if err != nil { + return fmt.Errorf("register workflow step vocabulary: %w", err) + } + control := controlplane.NewServer(resources, steps) versions, err := control.ImportConfig(ctx, b.cfg) if err != nil { return fmt.Errorf("import control-plane resources: %w", err) diff --git a/internal/app/archiemessaging/run.go b/internal/app/archiemessaging/run.go index 96e230a58..5cc3593f7 100644 --- a/internal/app/archiemessaging/run.go +++ b/internal/app/archiemessaging/run.go @@ -11,6 +11,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/messaging" "github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" + "github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps" "github.com/samcharles93/archie-core/internal/secret" ) @@ -30,6 +31,13 @@ func Run(ctx context.Context, o Options) error { defer closeGateway() health := newReadinessRegistry(cfg.Options, chat) + // The messaging process reads control-plane resources through the client, so + // it registers the workflow step vocabulary at its composition root, before + // the first resolution, like every other process that resolves one. + steps, err := workflowsteps.NewManager() + if err != nil { + return fmt.Errorf("register workflow step vocabulary: %w", err) + } var settings *messaging.SettingsCommand var closeStateStore func() if cfg.Options.StateStore.Target != "" { @@ -39,7 +47,7 @@ func Run(ctx context.Context, o Options) error { } closeStateStore = closeClient defer closeStateStore() - chatSettings, channelVersion, settingsErr := controlplane.NewRPCClient(stateStore.ControlPlane()).RuntimeChatConfig(ctx, config.ChatConfig{ + chatSettings, channelVersion, settingsErr := controlplane.NewRPCClient(stateStore.ControlPlane(), steps).RuntimeChatConfig(ctx, config.ChatConfig{ Telegram: cfg.Telegram, Email: cfg.Email, Webhook: cfg.Webhook, WebhookAddr: cfg.WebhookAddr, ShowToolCalls: cfg.ShowToolCalls, }) if settingsErr != nil { diff --git a/internal/app/controlplane/client.go b/internal/app/controlplane/client.go index d08e5e2c7..1a10e109c 100644 --- a/internal/app/controlplane/client.go +++ b/internal/app/controlplane/client.go @@ -17,13 +17,20 @@ import ( "github.com/samcharles93/archie-core/internal/infrastructure/cronstore" ) -type Client struct{ rpc pb.ControlPlaneServiceClient } - -func NewClient(conn grpc.ClientConnInterface) *Client { - return &Client{rpc: pb.NewControlPlaneServiceClient(conn)} +type Client struct { + rpc pb.ControlPlaneServiceClient + // steps is the step vocabulary this client validates and decodes workflow + // definitions against, resolved once by stepRegistry. + steps workflow.StepRegistry } -func NewRPCClient(client pb.ControlPlaneServiceClient) *Client { return &Client{rpc: client} } +func NewClient(conn grpc.ClientConnInterface, steps *workflow.Manager) *Client { + return &Client{rpc: pb.NewControlPlaneServiceClient(conn), steps: stepRegistry(steps)} +} + +func NewRPCClient(client pb.ControlPlaneServiceClient, steps *workflow.Manager) *Client { + return &Client{rpc: client, steps: stepRegistry(steps)} +} func (c *Client) Catalog(ctx context.Context) ([]*pb.ResourceDescriptor, error) { response, err := c.rpc.Catalog(ctx, &pb.CatalogRequest{}) @@ -38,7 +45,7 @@ func (c *Client) WorkflowDefinitions(ctx context.Context) (workflow.WorkflowDefi 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 } @@ -46,7 +53,7 @@ func (c *Client) WorkflowDefinitions(ctx context.Context) (workflow.WorkflowDefi // 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) + value, err := encodeWorkflowDefinitions(definitions, c.steps) if err != nil { return 0, err } diff --git a/internal/app/controlplane/controlplane.go b/internal/app/controlplane/controlplane.go index e3d487788..ac4650ea6 100644 --- a/internal/app/controlplane/controlplane.go +++ b/internal/app/controlplane/controlplane.go @@ -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,8 +42,12 @@ 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. +func NewServer(resources ResourceStore, steps *workflow.Manager) *Server { + registry := stepRegistry(steps) + definitions := builtinDefinitions(registry) byKind := make(map[string]Definition, len(definitions)) for _, definition := range definitions { byKind[definition.Kind] = definition diff --git a/internal/app/controlplane/controlplane_test.go b/internal/app/controlplane/controlplane_test.go index fd3dd59a6..a74fcc3e6 100644 --- a/internal/app/controlplane/controlplane_test.go +++ b/internal/app/controlplane/controlplane_test.go @@ -13,15 +13,28 @@ 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 +} + 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 := NewServer(resources, testSteps(t)).Catalog(t.Context(), &pb.CatalogRequest{}) if err != nil { t.Fatal(err) } @@ -48,7 +61,7 @@ func TestImportConfigSeedsWorkflowDefinitionsWithoutOverwritingOverride(t *testi resources := store.OpenTest(t) defer resources.Close() - server := NewServer(resources) + server := NewServer(resources, testSteps(t)) if _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil { t.Fatal(err) } @@ -64,7 +77,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 +101,7 @@ func TestImportConfigSeedsPersonasWithoutOverwritingEdits(t *testing.T) { resources := store.OpenTest(t) defer resources.Close() - server := NewServer(resources) + server := NewServer(resources, testSteps(t)) if _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil { t.Fatal(err) } @@ -126,7 +139,7 @@ func TestImportWorkflowExecutionSettingsDoesNotOverwriteExistingValue(t *testing resources := store.OpenTest(t) defer resources.Close() - server := NewServer(resources) + server := NewServer(resources, testSteps(t)) first := workflow.ExecutionSettings{MaxModelToolSteps: 10, MaxRuntime: time.Minute, MaxConsecutiveGateFailures: 2} if _, err := server.ImportWorkflowExecutionSettings(t.Context(), first); err != nil { t.Fatal(err) @@ -152,7 +165,7 @@ func TestRegistryRoutesAndValidatesDefinitions(t *testing.T) { resources := store.OpenTest(t) defer resources.Close() - server := NewServer(resources) + server := NewServer(resources, testSteps(t)) if _, err := server.ImportConfig(t.Context(), config.Config{Containers: config.ContainerConfig{PullPolicy: "missing"}}); err != nil { t.Fatal(err) } @@ -182,7 +195,7 @@ func TestProviderSeedKeepsReferencesAndNeverResolvedSecrets(t *testing.T) { resources := store.OpenTest(t) defer resources.Close() - server := NewServer(resources) + server := NewServer(resources, testSteps(t)) 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 +222,7 @@ func TestHistoryCarriesEveryRevisionWithItsAudit(t *testing.T) { resources := store.OpenTest(t) defer resources.Close() - server := NewServer(resources) + server := NewServer(resources, testSteps(t)) if _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil { t.Fatal(err) } diff --git a/internal/app/controlplane/definitions.go b/internal/app/controlplane/definitions.go index 59e390b0c..a02921ca0 100644 --- a/internal/app/controlplane/definitions.go +++ b/internal/app/controlplane/definitions.go @@ -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 diff --git a/internal/app/controlplane/runtime_config_test.go b/internal/app/controlplane/runtime_config_test.go index ec4c4ab4f..4d55c50ce 100644 --- a/internal/app/controlplane/runtime_config_test.go +++ b/internal/app/controlplane/runtime_config_test.go @@ -53,7 +53,7 @@ func TestRuntimeConfigUsesDatabaseResourcesAndPreservesBootstrapOnlySecrets(t *t ToolSettingsKind: map[string]any{"mcp_servers": []map[string]any{{"name": "docs", "transport": "http", "url": "https://mcp.example.com", "headers_configured": true}}, "policy": map[string]any{}, "web_fetch": map[string]any{}, "minimax": map[string]any{"enabled": false, "credential_configured": false}}, PluginSettingsKind: map[string]any{"plugin_dir": "/plugins", "module_dir": "/modules", "secret_engine_dir": "/secrets", "skills_dir": "/skills"}, ContainerRuntimePoliciesKind: config.ContainerConfig{LegacyEnabled: true, Image: "archie:next", PullPolicy: "missing"}, - }}) + }}, testSteps(t)) got, versions, err := client.RuntimeConfig(t.Context(), base) if err != nil { diff --git a/internal/app/controlplane/step_vocabulary_agreement_test.go b/internal/app/controlplane/step_vocabulary_agreement_test.go new file mode 100644 index 000000000..3626821fe --- /dev/null +++ b/internal/app/controlplane/step_vocabulary_agreement_test.go @@ -0,0 +1,291 @@ +// 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 every production resolution site with it. +// +// "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" + "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("control-plane 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 := NewRPCClient(rpc, steps) + + // 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) + } + }) + }) + } +} + +// 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 := NewServer(resources, steps) + + 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") +} diff --git a/internal/app/controlplane/workflow_definitions.go b/internal/app/controlplane/workflow_definitions.go index c4283b435..7dd175363 100644 --- a/internal/app/controlplane/workflow_definitions.go +++ b/internal/app/controlplane/workflow_definitions.go @@ -10,7 +10,15 @@ import ( const WorkflowDefinitionsKind = "workflow-definitions" -func workflowDefinitionsDefinition() Definition { +// stepRegistry is this package's single resolution site for the workflow step +// vocabulary. The manager is built at the composition root +// (infrastructure/workflowsteps.NewManager) and injected, so the State Store +// server -- the validating side -- and the control-plane client both resolve +// the vocabulary that composition root registered, and neither can validate a +// definition against a vocabulary the other does not have. +func stepRegistry(steps *workflow.Manager) workflow.StepRegistry { return steps.Registry() } + +func workflowDefinitionsDefinition(steps workflow.StepRegistry) Definition { return Definition{ Kind: WorkflowDefinitionsKind, Title: "Workflow definitions", @@ -23,14 +31,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) diff --git a/internal/domain/workflow/vocabulary.go b/internal/domain/workflow/vocabulary.go new file mode 100644 index 000000000..4158b4c3d --- /dev/null +++ b/internal/domain/workflow/vocabulary.go @@ -0,0 +1,162 @@ +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 both sides of the process +// boundary compare, and cannot be misread as a shipped stage. +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: both sides of the process boundary +// — the validating side (the State Store's control plane) and the executing +// side (archie-agent) — build a Manager at their composition root from the same +// provider set (internal/infrastructure/workflowsteps) and inject it, so a +// definition that validates on one side is compilable on the other by +// construction rather than by convention. +// +// Registration happens before the first resolution: a Manager handed to a +// consumer is not registered to afterwards. +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 +} diff --git a/internal/domain/workflow/vocabulary_test.go b/internal/domain/workflow/vocabulary_test.go new file mode 100644 index 000000000..6efbc7187 --- /dev/null +++ b/internal/domain/workflow/vocabulary_test.go @@ -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") + } +} diff --git a/internal/infrastructure/workflowsteps/workflowsteps.go b/internal/infrastructure/workflowsteps/workflowsteps.go new file mode 100644 index 000000000..cebc55256 --- /dev/null +++ b/internal/infrastructure/workflowsteps/workflowsteps.go @@ -0,0 +1,61 @@ +// Package workflowsteps is the compiled-in workflow step-type provider set: +// the one place a step type is bundled into every Archie binary. +// +// Both composition roots import it — internal/app/archied (which serves the +// State Store's validating side) and internal/app/agentworker (the executing +// side) — so the two sides register the same vocabulary by construction rather +// than by convention. Neither root keeps a package-level registry of its own. +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 every Archie process registers at its +// composition root, before the first resolution. 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 the Yaegi-interpreted plugins internal/plugin loads +// satisfy plugin.Plugin's metadata contract but cannot hand the host a working +// workflow.StepFactory. archie-agent links its own binary in any case. +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 +} diff --git a/internal/infrastructure/workflowsteps/workflowsteps_test.go b/internal/infrastructure/workflowsteps/workflowsteps_test.go new file mode 100644 index 000000000..f80da9889 --- /dev/null +++ b/internal/infrastructure/workflowsteps/workflowsteps_test.go @@ -0,0 +1,60 @@ +package workflowsteps + +import ( + "slices" + "testing" + + "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) + } + + want := make([]string, 0, len(workflow.BuiltinStepRegistry())) + for name := range workflow.BuiltinStepRegistry() { + want = append(want, name) + } + slices.Sort(want) + if got := manager.StepTypes(); !slices.Equal(got, want) { + t.Fatalf("registered vocabulary = %v, want the shipped stages %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) + } +} + +// 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()) + } +} From d4f35104e399cb177a848651091725d9cfe4363e Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 21 Sep 2026 19:46:05 +1000 Subject: [PATCH 2/5] test(workflowsteps): pin that the provider forwards the shipped factories Self-review of the fwmp shape: the provider enumerates BuiltinStepRegistry and forwards each factory, so no shipped behaviour changed -- but the one guard the refactor moved off the production path lost its coverage. "A shipped stage accepts no settings" was asserted only in internal/domain/workflow/definition_test.go through BuiltinStepRegistry, which production no longer calls; TestShippedVocabularyCoversEveryShippedStage compares names only, so a provider that rebuilt the factories instead of forwarding them would keep every name, lose the guard, and stay green. The new test drives every shipped definition through the registered vocabulary and asserts each step compiles to the shipped stage (not a rebuild named after the step type) and that settings are still refused. --- .../workflowsteps/workflowsteps_test.go | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/internal/infrastructure/workflowsteps/workflowsteps_test.go b/internal/infrastructure/workflowsteps/workflowsteps_test.go index f80da9889..a9fc1fe7e 100644 --- a/internal/infrastructure/workflowsteps/workflowsteps_test.go +++ b/internal/infrastructure/workflowsteps/workflowsteps_test.go @@ -2,6 +2,7 @@ package workflowsteps import ( "slices" + "strings" "testing" "github.com/samcharles93/archie-core/internal/domain/workflow" @@ -36,6 +37,47 @@ func TestShippedVocabularyCoversEveryShippedStage(t *testing.T) { } } +// 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 +// carries 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, which production no longer calls. +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 { + want := strings.TrimPrefix(step.Type, entry.ID+".") + if compiled.Stages[i].Name != want { + 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, want) + } + } + } + + 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` From 9fb65d0519c37beb2b6cebbf015feded6fce876a Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 21 Sep 2026 20:00:37 +1000 Subject: [PATCH 3/5] 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. --- .../app/agentworker/step_vocabulary_test.go | 61 ++++++++++++ internal/app/agentworker/task_execution.go | 6 ++ internal/app/agentworker/worker.go | 6 ++ internal/app/archied/bootstrap.go | 25 +++-- .../app/archied/control_plane_reload_test.go | 14 +-- internal/app/archied/state_store.go | 36 +++++-- internal/app/archied/step_vocabulary.go | 24 +++++ internal/app/archied/step_vocabulary_test.go | 98 +++++++++++++++++++ internal/app/archiemessaging/run.go | 10 +- internal/app/controlplane/client.go | 41 +++++--- internal/app/controlplane/controlplane.go | 12 ++- .../app/controlplane/controlplane_test.go | 26 +++-- .../app/controlplane/runtime_config_test.go | 2 +- .../step_vocabulary_agreement_test.go | 36 ++++++- .../app/controlplane/workflow_definitions.go | 21 ++-- internal/domain/workflow/vocabulary.go | 26 +++-- .../workflowsteps/workflowsteps.go | 21 ++-- .../workflowsteps/workflowsteps_test.go | 29 ++++-- 18 files changed, 398 insertions(+), 96 deletions(-) create mode 100644 internal/app/agentworker/step_vocabulary_test.go create mode 100644 internal/app/archied/step_vocabulary.go create mode 100644 internal/app/archied/step_vocabulary_test.go diff --git a/internal/app/agentworker/step_vocabulary_test.go b/internal/app/agentworker/step_vocabulary_test.go new file mode 100644 index 000000000..30894a5cb --- /dev/null +++ b/internal/app/agentworker/step_vocabulary_test.go @@ -0,0 +1,61 @@ +package agentworker + +import ( + "slices" + "testing" + + "gopkg.in/yaml.v3" + + "github.com/samcharles93/archie-core/internal/domain/workflow" +) + +// 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") + } + want := make([]string, 0, len(workflow.BuiltinStepRegistry())) + for name := range workflow.BuiltinStepRegistry() { + want = append(want, name) + } + slices.Sort(want) + if got := steps.StepTypes(); !slices.Equal(got, want) { + t.Fatalf("the composition root resolves %v, want the shared provider set's shipped stages %v", got, want) + } + 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") + } +} diff --git a/internal/app/agentworker/task_execution.go b/internal/app/agentworker/task_execution.go index 57098fe2f..8531d7e8e 100644 --- a/internal/app/agentworker/task_execution.go +++ b/internal/app/agentworker/task_execution.go @@ -327,6 +327,12 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen // 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() diff --git a/internal/app/agentworker/worker.go b/internal/app/agentworker/worker.go index 26bcaa779..5d279d8ad 100644 --- a/internal/app/agentworker/worker.go +++ b/internal/app/agentworker/worker.go @@ -64,6 +64,12 @@ type workerDependencies struct { 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 { diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 7c40b9cc8..a630caa34 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -54,7 +54,6 @@ import ( "github.com/samcharles93/archie-core/internal/infrastructure/skillcurator" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" "github.com/samcharles93/archie-core/internal/infrastructure/taskactions" - "github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps" "github.com/samcharles93/archie-core/internal/logging" "github.com/samcharles93/archie-core/internal/plugin" "github.com/samcharles93/archie-core/internal/plugin/pluginextract" @@ -117,6 +116,10 @@ type boot struct { stateStoreGrants *staterpc.GrantIssuer stateStoreToken string controlPlane *controlplane.Client + // 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. @@ -359,15 +362,23 @@ func (b *boot) openStateStoreAdapter() error { } b.stateStore = client // The daemon reads and replaces workflow definitions through the - // control-plane client, so it resolves the same step vocabulary the State - // Store server validates against: registered here, at the composition - // root, before the first read. - steps, err := workflowsteps.NewManager() + // workflow-definitions client, so it resolves the same step vocabulary the + // State Store server validates against: registered here, at the composition + // root, before the first read, through stepVocabulary (see + // step_vocabulary_test.go, which pins both archied roots to it). That + // agreement holds within one build: the State Store is a separate binary, + // and a skewed deploy is only fixed by a matching deploy. + steps, err := stepVocabulary() if err != nil { b.log.Error("register workflow step vocabulary", "err", err) return err } - b.controlPlane = controlplane.NewRPCClient(client.ControlPlane(), steps) + b.controlPlane = controlplane.NewRPCClient(client.ControlPlane()) + b.workflowDefinitions, err = controlplane.NewWorkflowDefinitionsClient(client.ControlPlane(), steps) + if err != nil { + b.log.Error("workflow definitions client", "err", err) + return err + } 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) @@ -1252,7 +1263,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 diff --git a/internal/app/archied/control_plane_reload_test.go b/internal/app/archied/control_plane_reload_test.go index d90785de5..348db1e66 100644 --- a/internal/app/archied/control_plane_reload_test.go +++ b/internal/app/archied/control_plane_reload_test.go @@ -14,20 +14,8 @@ import ( 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/configuration" - "github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps" ) -// reloadSteps builds the production workflow step vocabulary the reload tests' -// control-plane client resolves definitions against. -func reloadSteps(t *testing.T) *workflow.Manager { - t.Helper() - steps, err := workflowsteps.NewManager() - if err != nil { - t.Fatalf("build workflow step vocabulary: %v", err) - } - return steps -} - // controlPlaneStub answers Query from a fixed resource map. queryErr, when // set, fails every Query so a test can drive the unreachable-State-Store // path. @@ -99,7 +87,7 @@ func newReloadBoot(t *testing.T, stub *controlPlaneStub) *boot { b := &boot{ cfg: fileConfig(), log: slog.New(slog.DiscardHandler), - controlPlane: controlplane.NewRPCClient(stub, reloadSteps(t)), + controlPlane: controlplane.NewRPCClient(stub), } b.cfgHolder = config.NewHolder(b.cfg) return b diff --git a/internal/app/archied/state_store.go b/internal/app/archied/state_store.go index 34c79632e..d2a1da380 100644 --- a/internal/app/archied/state_store.go +++ b/internal/app/archied/state_store.go @@ -30,7 +30,6 @@ import ( "github.com/samcharles93/archie-core/internal/infrastructure/cronstore" "github.com/samcharles93/archie-core/internal/infrastructure/readiness" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" - "github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps" "github.com/samcharles93/archie-core/internal/store" ) @@ -101,16 +100,12 @@ func RunStateStore(ctx context.Context, options StateStoreOptions) error { if !ok { return fmt.Errorf("state store does not support control-plane resources") } - // The validating side's 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 a definition this - // server admits is compilable there. - steps, err := workflowsteps.NewManager() + // 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 fmt.Errorf("register workflow step vocabulary: %w", err) + return err } - control := controlplane.NewServer(resources, steps) versions, err := control.ImportConfig(ctx, b.cfg) if err != nil { return fmt.Errorf("import control-plane resources: %w", err) @@ -147,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 diff --git a/internal/app/archied/step_vocabulary.go b/internal/app/archied/step_vocabulary.go new file mode 100644 index 000000000..a59c1ba7e --- /dev/null +++ b/internal/app/archied/step_vocabulary.go @@ -0,0 +1,24 @@ +package archied + +import ( + "github.com/samcharles93/archie-core/internal/domain/workflow" + "github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps" +) + +// stepVocabulary builds the workflow step vocabulary this archied process +// resolves workflow definitions against: the shared provider set +// (internal/infrastructure/workflowsteps), registered here at the composition +// root, before the first resolution. +// +// Both archied roots call it -- RunStateStore (the State Store's validating +// side) and openStateStoreAdapter (the daemon's control-plane client) -- so +// neither can register a vocabulary of its own. It is a named function so that +// step_vocabulary_test.go can fail if it stops using the shared provider set; +// the roots themselves own a SQLite file and dial gRPC, so the test asserts +// they call it 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() } diff --git a/internal/app/archied/step_vocabulary_test.go b/internal/app/archied/step_vocabulary_test.go new file mode 100644 index 000000000..a1f63a085 --- /dev/null +++ b/internal/app/archied/step_vocabulary_test.go @@ -0,0 +1,98 @@ +package archied + +import ( + "go/ast" + "go/parser" + "go/token" + "slices" + "testing" + + "gopkg.in/yaml.v3" + + "github.com/samcharles93/archie-core/internal/domain/workflow" +) + +// 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 + }}} +} + +// TestStepVocabularyRegistersTheSharedProviderSet pins the unit both archied +// roots resolve their vocabulary from. Handing this function an empty manager +// (workflow.NewManager) would leave the State Store unable to admit any stored +// definition and the daemon unable to decode one. +func TestStepVocabularyRegistersTheSharedProviderSet(t *testing.T) { + steps, err := stepVocabulary() + if err != nil { + t.Fatalf("stepVocabulary: %v", err) + } + if steps == nil { + t.Fatal("stepVocabulary registered no workflow step vocabulary") + } + want := make([]string, 0, len(workflow.BuiltinStepRegistry())) + for name := range workflow.BuiltinStepRegistry() { + want = append(want, name) + } + slices.Sort(want) + if got := steps.StepTypes(); !slices.Equal(got, want) { + t.Fatalf("archied resolves %v, want the shared provider set's shipped stages %v", got, want) + } + if err := steps.Register(stepVocabularyProbe{}); err != nil { + t.Fatalf("register a provider through archied's manager: %v", err) + } + if _, resolved := steps.Registry()["probe.registered"]; !resolved { + t.Fatal("a provider registered through archied's manager did not reach its vocabulary") + } +} + +// TestArchiedRootsResolveTheStepVocabularyFromThatFunction pins that reading +// through stepVocabulary is how both roots reach the vocabulary. Neither root +// can be executed in a unit test -- RunStateStore owns a SQLite file and +// listen address, openStateStoreAdapter dials the State Store -- so the calls +// 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 +// would resolve a vocabulary of its own and silently lose the shipped stages. +func TestArchiedRootsResolveTheStepVocabularyFromThatFunction(t *testing.T) { + for _, link := range []struct{ file, function, resolves string }{ + {"state_store.go", "RunStateStore", "openStateStoreControlPlane"}, + // RunStateStore delegates to this function, which is where the shipped + // stages enter this process. + {"state_store.go", "openStateStoreControlPlane", "stepVocabulary"}, + {"bootstrap.go", "openStateStoreAdapter", "stepVocabulary"}, + } { + t.Run(link.function+"->"+link.resolves, func(t *testing.T) { + file, err := parser.ParseFile(token.NewFileSet(), link.file, nil, 0) + if err != nil { + t.Fatal(err) + } + if identCallPosition(methodBody(t, file, link.function), link.resolves) == token.NoPos { + t.Errorf("%s does not reach its step vocabulary through %s()", link.function, link.resolves) + } + }) + } +} + +// 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 +} diff --git a/internal/app/archiemessaging/run.go b/internal/app/archiemessaging/run.go index 5cc3593f7..96e230a58 100644 --- a/internal/app/archiemessaging/run.go +++ b/internal/app/archiemessaging/run.go @@ -11,7 +11,6 @@ import ( "github.com/samcharles93/archie-core/internal/domain/messaging" "github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" - "github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps" "github.com/samcharles93/archie-core/internal/secret" ) @@ -31,13 +30,6 @@ func Run(ctx context.Context, o Options) error { defer closeGateway() health := newReadinessRegistry(cfg.Options, chat) - // The messaging process reads control-plane resources through the client, so - // it registers the workflow step vocabulary at its composition root, before - // the first resolution, like every other process that resolves one. - steps, err := workflowsteps.NewManager() - if err != nil { - return fmt.Errorf("register workflow step vocabulary: %w", err) - } var settings *messaging.SettingsCommand var closeStateStore func() if cfg.Options.StateStore.Target != "" { @@ -47,7 +39,7 @@ func Run(ctx context.Context, o Options) error { } closeStateStore = closeClient defer closeStateStore() - chatSettings, channelVersion, settingsErr := controlplane.NewRPCClient(stateStore.ControlPlane(), steps).RuntimeChatConfig(ctx, config.ChatConfig{ + chatSettings, channelVersion, settingsErr := controlplane.NewRPCClient(stateStore.ControlPlane()).RuntimeChatConfig(ctx, config.ChatConfig{ Telegram: cfg.Telegram, Email: cfg.Email, Webhook: cfg.Webhook, WebhookAddr: cfg.WebhookAddr, ShowToolCalls: cfg.ShowToolCalls, }) if settingsErr != nil { diff --git a/internal/app/controlplane/client.go b/internal/app/controlplane/client.go index 1a10e109c..de3583b1d 100644 --- a/internal/app/controlplane/client.go +++ b/internal/app/controlplane/client.go @@ -17,19 +17,36 @@ import ( "github.com/samcharles93/archie-core/internal/infrastructure/cronstore" ) -type Client struct { - rpc pb.ControlPlaneServiceClient - // steps is the step vocabulary this client validates and decodes workflow - // definitions against, resolved once by stepRegistry. +// 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 -- +// needs no provider set and cannot be failed by one. +type Client struct{ rpc pb.ControlPlaneServiceClient } + +func NewClient(conn grpc.ClientConnInterface) *Client { + return &Client{rpc: pb.NewControlPlaneServiceClient(conn)} +} + +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 NewClient(conn grpc.ClientConnInterface, steps *workflow.Manager) *Client { - return &Client{rpc: pb.NewControlPlaneServiceClient(conn), steps: stepRegistry(steps)} -} - -func NewRPCClient(client pb.ControlPlaneServiceClient, steps *workflow.Manager) *Client { - return &Client{rpc: client, steps: stepRegistry(steps)} +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) { @@ -40,7 +57,7 @@ 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) @@ -52,7 +69,7 @@ func (c *Client) WorkflowDefinitions(ctx context.Context) (workflow.WorkflowDefi // 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) { +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 diff --git a/internal/app/controlplane/controlplane.go b/internal/app/controlplane/controlplane.go index ac4650ea6..47a11ad89 100644 --- a/internal/app/controlplane/controlplane.go +++ b/internal/app/controlplane/controlplane.go @@ -44,15 +44,19 @@ type Server struct { // 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. -func NewServer(resources ResourceStore, steps *workflow.Manager) *Server { - registry := stepRegistry(steps) +// 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) { diff --git a/internal/app/controlplane/controlplane_test.go b/internal/app/controlplane/controlplane_test.go index a74fcc3e6..499ce2c61 100644 --- a/internal/app/controlplane/controlplane_test.go +++ b/internal/app/controlplane/controlplane_test.go @@ -29,12 +29,24 @@ func testSteps(t *testing.T) *workflow.Manager { 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, testSteps(t)).Catalog(t.Context(), &pb.CatalogRequest{}) + catalog, err := testServer(t, resources).Catalog(t.Context(), &pb.CatalogRequest{}) if err != nil { t.Fatal(err) } @@ -61,7 +73,7 @@ func TestImportConfigSeedsWorkflowDefinitionsWithoutOverwritingOverride(t *testi resources := store.OpenTest(t) defer resources.Close() - server := NewServer(resources, testSteps(t)) + server := testServer(t, resources) if _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil { t.Fatal(err) } @@ -101,7 +113,7 @@ func TestImportConfigSeedsPersonasWithoutOverwritingEdits(t *testing.T) { resources := store.OpenTest(t) defer resources.Close() - server := NewServer(resources, testSteps(t)) + server := testServer(t, resources) if _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil { t.Fatal(err) } @@ -139,7 +151,7 @@ func TestImportWorkflowExecutionSettingsDoesNotOverwriteExistingValue(t *testing resources := store.OpenTest(t) defer resources.Close() - server := NewServer(resources, testSteps(t)) + 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) @@ -165,7 +177,7 @@ func TestRegistryRoutesAndValidatesDefinitions(t *testing.T) { resources := store.OpenTest(t) defer resources.Close() - server := NewServer(resources, testSteps(t)) + server := testServer(t, resources) if _, err := server.ImportConfig(t.Context(), config.Config{Containers: config.ContainerConfig{PullPolicy: "missing"}}); err != nil { t.Fatal(err) } @@ -195,7 +207,7 @@ func TestProviderSeedKeepsReferencesAndNeverResolvedSecrets(t *testing.T) { resources := store.OpenTest(t) defer resources.Close() - server := NewServer(resources, testSteps(t)) + 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) @@ -222,7 +234,7 @@ func TestHistoryCarriesEveryRevisionWithItsAudit(t *testing.T) { resources := store.OpenTest(t) defer resources.Close() - server := NewServer(resources, testSteps(t)) + server := testServer(t, resources) if _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil { t.Fatal(err) } diff --git a/internal/app/controlplane/runtime_config_test.go b/internal/app/controlplane/runtime_config_test.go index 4d55c50ce..ec4c4ab4f 100644 --- a/internal/app/controlplane/runtime_config_test.go +++ b/internal/app/controlplane/runtime_config_test.go @@ -53,7 +53,7 @@ func TestRuntimeConfigUsesDatabaseResourcesAndPreservesBootstrapOnlySecrets(t *t ToolSettingsKind: map[string]any{"mcp_servers": []map[string]any{{"name": "docs", "transport": "http", "url": "https://mcp.example.com", "headers_configured": true}}, "policy": map[string]any{}, "web_fetch": map[string]any{}, "minimax": map[string]any{"enabled": false, "credential_configured": false}}, PluginSettingsKind: map[string]any{"plugin_dir": "/plugins", "module_dir": "/modules", "secret_engine_dir": "/secrets", "skills_dir": "/skills"}, ContainerRuntimePoliciesKind: config.ContainerConfig{LegacyEnabled: true, Image: "archie:next", PullPolicy: "missing"}, - }}, testSteps(t)) + }}) got, versions, err := client.RuntimeConfig(t.Context(), base) if err != nil { diff --git a/internal/app/controlplane/step_vocabulary_agreement_test.go b/internal/app/controlplane/step_vocabulary_agreement_test.go index 3626821fe..d4a4d9ab5 100644 --- a/internal/app/controlplane/step_vocabulary_agreement_test.go +++ b/internal/app/controlplane/step_vocabulary_agreement_test.go @@ -121,13 +121,16 @@ func TestEveryProductionResolutionSiteResolvesTheRegisteredStepType(t *testing.T } }) - t.Run("control-plane client", func(t *testing.T) { + 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 := NewRPCClient(rpc, steps) + 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()) @@ -173,6 +176,30 @@ func TestEveryProductionResolutionSiteResolvesTheRegisteredStepType(t *testing.T } } +// 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 @@ -226,7 +253,10 @@ func admitThroughStateStore(t *testing.T, steps *workflow.Manager, stepType stri t.Errorf("close test store: %v", closeErr) } }) - server := NewServer(resources, steps) + 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 diff --git a/internal/app/controlplane/workflow_definitions.go b/internal/app/controlplane/workflow_definitions.go index 7dd175363..72c5dae20 100644 --- a/internal/app/controlplane/workflow_definitions.go +++ b/internal/app/controlplane/workflow_definitions.go @@ -2,6 +2,7 @@ package controlplane import ( "encoding/json" + "errors" "fmt" "github.com/samcharles93/archie-core/internal/config" @@ -11,12 +12,20 @@ import ( const WorkflowDefinitionsKind = "workflow-definitions" // stepRegistry is this package's single resolution site for the workflow step -// vocabulary. The manager is built at the composition root -// (infrastructure/workflowsteps.NewManager) and injected, so the State Store -// server -- the validating side -- and the control-plane client both resolve -// the vocabulary that composition root registered, and neither can validate a -// definition against a vocabulary the other does not have. -func stepRegistry(steps *workflow.Manager) workflow.StepRegistry { return steps.Registry() } +// 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{ diff --git a/internal/domain/workflow/vocabulary.go b/internal/domain/workflow/vocabulary.go index 4158b4c3d..ca401f44f 100644 --- a/internal/domain/workflow/vocabulary.go +++ b/internal/domain/workflow/vocabulary.go @@ -12,8 +12,10 @@ import ( // 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 both sides of the process -// boundary compare, and cannot be misread as a shipped stage. +// 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 @@ -40,15 +42,19 @@ type StepTypeProvider interface { // parsed and compiled against. // // It is a constructed, injected value. There is deliberately no package-level -// registry and no init()-time registration: both sides of the process boundary -// — the validating side (the State Store's control plane) and the executing -// side (archie-agent) — build a Manager at their composition root from the same -// provider set (internal/infrastructure/workflowsteps) and inject it, so a -// definition that validates on one side is compilable on the other by -// construction rather than by convention. +// 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 happens before the first resolution: a Manager handed to a -// consumer is not registered to afterwards. +// 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 diff --git a/internal/infrastructure/workflowsteps/workflowsteps.go b/internal/infrastructure/workflowsteps/workflowsteps.go index cebc55256..ed51d52d7 100644 --- a/internal/infrastructure/workflowsteps/workflowsteps.go +++ b/internal/infrastructure/workflowsteps/workflowsteps.go @@ -1,10 +1,13 @@ // Package workflowsteps is the compiled-in workflow step-type provider set: // the one place a step type is bundled into every Archie binary. // -// Both composition roots import it — internal/app/archied (which serves the -// State Store's validating side) and internal/app/agentworker (the executing -// side) — so the two sides register the same vocabulary by construction rather -// than by convention. Neither root keeps a package-level registry of its own. +// Three composition roots import it, and each resolves a workflow step type: +// archied's RunStateStore (the State Store's validating side), archied's +// openStateStoreAdapter (the daemon's workflow-definitions client) and +// agentworker's productionWorkerDependencies (the executing side). Sharing one +// package is what keeps them registering the same vocabulary rather than one +// of them keeping a provider set of its own. archie-messaging resolves no step +// type and does not import it. package workflowsteps import ( @@ -38,9 +41,13 @@ func (shippedStages) StepTypes() []workflow.StepType { // 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 the Yaegi-interpreted plugins internal/plugin loads -// satisfy plugin.Plugin's metadata contract but cannot hand the host a working -// workflow.StepFactory. archie-agent links its own binary in any case. +// 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{}} } diff --git a/internal/infrastructure/workflowsteps/workflowsteps_test.go b/internal/infrastructure/workflowsteps/workflowsteps_test.go index a9fc1fe7e..33657931c 100644 --- a/internal/infrastructure/workflowsteps/workflowsteps_test.go +++ b/internal/infrastructure/workflowsteps/workflowsteps_test.go @@ -5,6 +5,8 @@ import ( "strings" "testing" + "gopkg.in/yaml.v3" + "github.com/samcharles93/archie-core/internal/domain/workflow" ) @@ -39,11 +41,12 @@ func TestShippedVocabularyCoversEveryShippedStage(t *testing.T) { // 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 -// carries 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, which production no longer calls. +// 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, which production no longer calls. func TestShippedStagesKeepTheirBehaviourThroughTheManager(t *testing.T) { t.Parallel() @@ -66,9 +69,19 @@ func TestShippedStagesKeepTheirBehaviourThroughTheManager(t *testing.T) { t.Fatalf("%s compiled %d stages, want %d", entry.ID, len(compiled.Stages), len(definition.Steps)) } for i, step := range definition.Steps { - want := strings.TrimPrefix(step.Type, entry.ID+".") - if compiled.Stages[i].Name != want { - 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, want) + // 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) } } } From b4aa56dcb30cf0b421d3703f37cde85b8d4c1919 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 21 Sep 2026 20:22:44 +1000 Subject: [PATCH 4/5] fix(archied): register the step vocabulary only where a root resolves it Review pass on the step-vocabulary shape. The gateway root shared openStateStoreAdapter with the daemon, so it registered a step vocabulary and built a workflow-definitions client it never read: the same dead vocabulary the previous commit removed from internal/app/archiemessaging, reintroduced through the shared adapter, and able to fail the gateway's boot the day a provider set can fail to load. The vocabulary and the client now belong to the daemon root alone (openDaemonWorkflowDefinitions, called by Run before buildDaemon captures it), which is what Client's "a process that never reads or writes a workflow definition needs no provider set and cannot be failed by one" already claimed. The root guard was weaker than its own comment: it asserted that a root calls stepVocabulary(), not that the manager returned is the one handed to NewServer/NewWorkflowDefinitionsClient, so a root could call it and inject an empty manager and keep every test green. The pin now asserts the data flow (both halves mutation-checked), plus Run's ordering -- after openStateStoreAdapter, before buildDaemon. Three root guards asserted exact equality with workflow.BuiltinStepRegistry(), which contradicted the extension path they guard: adding a provider to workflowsteps.Providers() -- the documented way a step type arrives -- failed all three, and the expectation could not be satisfied by editing it. They now assert what their doc says (every shipped stage present) plus provenance (every name resolved is declared by the shared provider set), and the workflowsteps guard derives its expectation from Providers() so both sides move together. New guard on the defect class the bead exists for: TestNoProductionSiteReaches- ForTheBuiltinStepRegistry scans the module and fails if any non-test file outside the domain declaration and the shipped provider names BuiltinStepRegistry, which the agreement test cannot see for a sixth resolution site added later. Claim-vs-code corrections: openStateStoreAdapter "reads and replaces" -> the daemon only reads, and ReplaceWorkflowDefinitions has no production caller yet; workflowsteps' package/Providers docs no longer claim every Archie binary registers the set (archie-gateway, archie-messaging, archie-playbooks and archie-ui do not); the shipped-provider test no longer says production does not call BuiltinStepRegistry, which is false -- production calls it only there. --- .../app/agentworker/step_vocabulary_test.go | 38 ++- internal/app/archied/bootstrap.go | 33 ++- internal/app/archied/main.go | 9 + internal/app/archied/step_vocabulary.go | 53 +++- internal/app/archied/step_vocabulary_test.go | 234 +++++++++++++++--- internal/app/controlplane/client.go | 7 +- .../step_vocabulary_agreement_test.go | 78 +++++- .../workflowsteps/workflowsteps.go | 24 +- .../workflowsteps/workflowsteps_test.go | 33 ++- 9 files changed, 418 insertions(+), 91 deletions(-) diff --git a/internal/app/agentworker/step_vocabulary_test.go b/internal/app/agentworker/step_vocabulary_test.go index 30894a5cb..8f64d5eef 100644 --- a/internal/app/agentworker/step_vocabulary_test.go +++ b/internal/app/agentworker/step_vocabulary_test.go @@ -7,6 +7,7 @@ import ( "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 @@ -44,13 +45,27 @@ func requireSharedStepVocabulary(t *testing.T, steps *workflow.Manager) { if steps == nil { t.Fatal("the composition root registered no workflow step vocabulary") } - want := make([]string, 0, len(workflow.BuiltinStepRegistry())) + 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() { - want = append(want, name) + if !slices.Contains(got, name) { + t.Errorf("the composition root resolves %v, which is missing the shipped stage %q", got, name) + } } - slices.Sort(want) - if got := steps.StepTypes(); !slices.Equal(got, want) { - t.Fatalf("the composition root resolves %v, want the shared provider set's shipped stages %v", got, want) + // 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) @@ -59,3 +74,16 @@ func requireSharedStepVocabulary(t *testing.T, steps *workflow.Manager) { 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 +} diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index a630caa34..81d22d283 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -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,11 @@ 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. @@ -361,24 +367,15 @@ func (b *boot) openStateStoreAdapter() error { return err } b.stateStore = client - // The daemon reads and replaces workflow definitions through the - // workflow-definitions client, so it resolves the same step vocabulary the - // State Store server validates against: registered here, at the composition - // root, before the first read, through stepVocabulary (see - // step_vocabulary_test.go, which pins both archied roots to it). That - // agreement holds within one build: the State Store is a separate binary, - // and a skewed deploy is only fixed by a matching deploy. - steps, err := stepVocabulary() - if err != nil { - b.log.Error("register workflow step vocabulary", "err", err) - return err - } - b.controlPlane = controlplane.NewRPCClient(client.ControlPlane()) - b.workflowDefinitions, err = controlplane.NewWorkflowDefinitionsClient(client.ControlPlane(), steps) - if err != nil { - b.log.Error("workflow definitions client", "err", err) - return err - } + // 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) diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index 30fc84727..8ccca99c7 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -379,6 +379,15 @@ func Run() int { //nolint:cyclop,funlen // the composition root's setup sequence if err := b.openStateStoreAdapter(); err != nil { return 1 } + // The daemon resolves workflow step types through its workflow-definitions + // client, so it registers the step vocabulary here, at its own composition + // root, before buildDaemon captures the client. The gateway root shares + // openStateStoreAdapter and resolves no step type, so the vocabulary is built + // by this root alone (step_vocabulary_test.go pins the cut). + if err := b.openDaemonWorkflowDefinitions(); err != nil { + b.log.Error("workflow definitions client", "err", err) + return 1 + } if err := b.loadRuntimeConfig(ctx); err != nil { b.log.Error("runtime settings unavailable", "err", err) return 1 diff --git a/internal/app/archied/step_vocabulary.go b/internal/app/archied/step_vocabulary.go index a59c1ba7e..76eef2c2c 100644 --- a/internal/app/archied/step_vocabulary.go +++ b/internal/app/archied/step_vocabulary.go @@ -1,24 +1,57 @@ 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 this archied process -// resolves workflow definitions against: the shared provider set -// (internal/infrastructure/workflowsteps), registered here at the composition -// root, before the first resolution. +// 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. // -// Both archied roots call it -- RunStateStore (the State Store's validating -// side) and openStateStoreAdapter (the daemon's control-plane client) -- so -// neither can register a vocabulary of its own. It is a named function so that -// step_vocabulary_test.go can fail if it stops using the shared provider set; -// the roots themselves own a SQLite file and dial gRPC, so the test asserts -// they call it by parsing their bodies. +// 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 +} diff --git a/internal/app/archied/step_vocabulary_test.go b/internal/app/archied/step_vocabulary_test.go index a1f63a085..dca53146d 100644 --- a/internal/app/archied/step_vocabulary_test.go +++ b/internal/app/archied/step_vocabulary_test.go @@ -10,6 +10,7 @@ import ( "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 @@ -24,61 +25,214 @@ func (stepVocabularyProbe) StepTypes() []workflow.StepType { }}} } -// TestStepVocabularyRegistersTheSharedProviderSet pins the unit both archied -// roots resolve their vocabulary from. Handing this function an empty manager -// (workflow.NewManager) would leave the State Store unable to admit any stored -// definition and the daemon unable to decode one. +// 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) } - if steps == nil { - t.Fatal("stepVocabulary registered no workflow step vocabulary") - } - want := make([]string, 0, len(workflow.BuiltinStepRegistry())) - for name := range workflow.BuiltinStepRegistry() { - want = append(want, name) - } - slices.Sort(want) - if got := steps.StepTypes(); !slices.Equal(got, want) { - t.Fatalf("archied resolves %v, want the shared provider set's shipped stages %v", got, want) - } - if err := steps.Register(stepVocabularyProbe{}); err != nil { - t.Fatalf("register a provider through archied's manager: %v", err) - } - if _, resolved := steps.Registry()["probe.registered"]; !resolved { - t.Fatal("a provider registered through archied's manager did not reach its vocabulary") - } + requireSharedStepVocabulary(t, steps) } -// TestArchiedRootsResolveTheStepVocabularyFromThatFunction pins that reading -// through stepVocabulary is how both roots reach the vocabulary. Neither root -// can be executed in a unit test -- RunStateStore owns a SQLite file and -// listen address, openStateStoreAdapter dials the State Store -- so the calls -// 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 -// would resolve a vocabulary of its own and silently lose the shipped stages. +// 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, resolves string }{ - {"state_store.go", "RunStateStore", "openStateStoreControlPlane"}, - // RunStateStore delegates to this function, which is where the shipped - // stages enter this process. - {"state_store.go", "openStateStoreControlPlane", "stepVocabulary"}, - {"bootstrap.go", "openStateStoreAdapter", "stepVocabulary"}, + 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+"->"+link.resolves, func(t *testing.T) { - file, err := parser.ParseFile(token.NewFileSet(), link.file, nil, 0) - if err != nil { - t.Fatal(err) + 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 identCallPosition(methodBody(t, file, link.function), link.resolves) == token.NoPos { - t.Errorf("%s does not reach its step vocabulary through %s()", link.function, link.resolves) + 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") + } + + run := parsedBody(t, "main.go", "Run") + adapter := methodCallPosition(run, "openStateStoreAdapter") + wiring := methodCallPosition(run, "openDaemonWorkflowDefinitions") + build := methodCallPosition(run, "buildDaemon") + if wiring == token.NoPos { + t.Fatal("Run 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("Run 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) + } + if build == token.NoPos || wiring > build { + t.Errorf("Run builds the workflow-definitions client at %v, after buildDaemon at %v: the daemon would capture no definitions surface", wiring, build) + } +} + +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 { diff --git a/internal/app/controlplane/client.go b/internal/app/controlplane/client.go index de3583b1d..f1e1e1c0d 100644 --- a/internal/app/controlplane/client.go +++ b/internal/app/controlplane/client.go @@ -20,7 +20,8 @@ import ( // 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 -- +// 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 } @@ -69,6 +70,10 @@ func (c *WorkflowDefinitionsClient) WorkflowDefinitions(ctx context.Context) (wo // ReplaceWorkflowDefinitions replaces the collection. Passing // workflow.ShippedDefinitions() restores all shipped definitions while keeping // the previous override in resource history. +// +// 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 { diff --git a/internal/app/controlplane/step_vocabulary_agreement_test.go b/internal/app/controlplane/step_vocabulary_agreement_test.go index d4a4d9ab5..4c8a37f4f 100644 --- a/internal/app/controlplane/step_vocabulary_agreement_test.go +++ b/internal/app/controlplane/step_vocabulary_agreement_test.go @@ -3,7 +3,11 @@ // 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 every production resolution site with it. +// 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 @@ -15,6 +19,11 @@ package controlplane import ( "context" "encoding/json" + "go/ast" + "go/parser" + "go/token" + "io/fs" + "path/filepath" "strings" "testing" @@ -319,3 +328,70 @@ func (c *definitionsClient) Command(_ context.Context, request *pb.CommandReques 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") + } +} diff --git a/internal/infrastructure/workflowsteps/workflowsteps.go b/internal/infrastructure/workflowsteps/workflowsteps.go index ed51d52d7..7de185f22 100644 --- a/internal/infrastructure/workflowsteps/workflowsteps.go +++ b/internal/infrastructure/workflowsteps/workflowsteps.go @@ -1,13 +1,15 @@ // Package workflowsteps is the compiled-in workflow step-type provider set: -// the one place a step type is bundled into every Archie binary. +// 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. // -// Three composition roots import it, and each resolves a workflow step type: -// archied's RunStateStore (the State Store's validating side), archied's -// openStateStoreAdapter (the daemon's workflow-definitions client) and -// agentworker's productionWorkerDependencies (the executing side). Sharing one -// package is what keeps them registering the same vocabulary rather than one -// of them keeping a provider set of its own. archie-messaging resolves no step -// type and does not import it. +// 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 ( @@ -36,8 +38,10 @@ func (shippedStages) StepTypes() []workflow.StepType { return stepTypes } -// Providers returns the provider set every Archie process registers at its -// composition root, before the first resolution. A step type added here becomes +// 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 diff --git a/internal/infrastructure/workflowsteps/workflowsteps_test.go b/internal/infrastructure/workflowsteps/workflowsteps_test.go index 33657931c..ee9ad4d70 100644 --- a/internal/infrastructure/workflowsteps/workflowsteps_test.go +++ b/internal/infrastructure/workflowsteps/workflowsteps_test.go @@ -22,13 +22,20 @@ func TestShippedVocabularyCoversEveryShippedStage(t *testing.T) { t.Fatalf("NewManager: %v", err) } - want := make([]string, 0, len(workflow.BuiltinStepRegistry())) + got := manager.StepTypes() + // Every shipped stage is present... for name := range workflow.BuiltinStepRegistry() { - want = append(want, name) + if !slices.Contains(got, name) { + t.Errorf("registered vocabulary %v is missing the shipped stage %q", got, name) + } } - slices.Sort(want) - if got := manager.StepTypes(); !slices.Equal(got, want) { - t.Fatalf("registered vocabulary = %v, want the shipped stages %v", got, want) + // ...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 @@ -39,6 +46,19 @@ func TestShippedVocabularyCoversEveryShippedStage(t *testing.T) { } } +// 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 @@ -46,7 +66,8 @@ func TestShippedVocabularyCoversEveryShippedStage(t *testing.T) { // 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, which production no longer calls. +// 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() From fe733b9bd1f376d95b9eaf34628bcd9fa0d23c6f Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 21 Sep 2026 20:29:20 +1000 Subject: [PATCH 5/5] refactor(archied): fold the daemon's state surfaces into one boot step Run's added openDaemonWorkflowDefinitions guard pushed it to gocyclo 21 (.golangci.yml's budget is 20). openDaemonStateSurfaces owns the pair -- adapter, then the definitions client on its transport -- so Run keeps one branch for the whole sequence and no suppression is added. step_vocabulary_test.go's pin moves with the sequence: it still asserts adapter before client, client before buildDaemon, and now also that Run opens neither half directly, so the ordering has exactly one call site. Behaviour is unchanged; the gateway root still calls openStateStoreAdapter alone and resolves no step vocabulary. --- internal/app/archied/main.go | 28 ++++++++--------- internal/app/archied/step_vocabulary.go | 25 +++++++++++++++ internal/app/archied/step_vocabulary_test.go | 32 +++++++++++++++----- 3 files changed, 62 insertions(+), 23 deletions(-) diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index 8ccca99c7..37870ec3f 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -370,22 +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 { - return 1 - } - // The daemon resolves workflow step types through its workflow-definitions - // client, so it registers the step vocabulary here, at its own composition - // root, before buildDaemon captures the client. The gateway root shares - // openStateStoreAdapter and resolves no step type, so the vocabulary is built - // by this root alone (step_vocabulary_test.go pins the cut). - if err := b.openDaemonWorkflowDefinitions(); err != nil { - b.log.Error("workflow definitions client", "err", err) + // 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 { diff --git a/internal/app/archied/step_vocabulary.go b/internal/app/archied/step_vocabulary.go index 76eef2c2c..8815c15ce 100644 --- a/internal/app/archied/step_vocabulary.go +++ b/internal/app/archied/step_vocabulary.go @@ -55,3 +55,28 @@ func (b *boot) openDaemonWorkflowDefinitions() error { 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 +} diff --git a/internal/app/archied/step_vocabulary_test.go b/internal/app/archied/step_vocabulary_test.go index dca53146d..ed0b068c4 100644 --- a/internal/app/archied/step_vocabulary_test.go +++ b/internal/app/archied/step_vocabulary_test.go @@ -138,18 +138,36 @@ func TestOnlyTheDaemonRootRegistersAStepVocabulary(t *testing.T) { 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") - adapter := methodCallPosition(run, "openStateStoreAdapter") - wiring := methodCallPosition(run, "openDaemonWorkflowDefinitions") + 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("Run never builds the daemon's workflow-definitions client; every task pin would fall back to the shipped definitions") + 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("Run 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) - } - if build == token.NoPos || wiring > build { - t.Errorf("Run builds the workflow-definitions client at %v, after buildDaemon at %v: the daemon would capture no definitions surface", wiring, build) + 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) } }