feat(workflow): switch step runs the case matching a reference

This commit is contained in:
sam committed 2026-10-10 10:52:52 +11:00
1 parent 8a2354447e
commit 28032ddbd4
6 files changed
+164 -11

No files matched your search

+1 -1
View File
@@ -292,7 +292,7 @@ func findStep(steps []StepRecord, id string) (StepRecord, bool) {
if step.ID == id {
return step, true
}
for _, branch := range step.Parallel {
for _, branch := range step.branches() {
if found, ok := findStep(branch, id); ok {
return found, true
}
+21
View File
@@ -53,8 +53,20 @@ type StepRecord struct {
// Parallel makes this step a set of named branches that run at the same
// time instead of a typed step. Each branch is a list of steps.
Parallel map[string][]StepRecord `yaml:"parallel,omitempty" json:"parallel,omitempty"`
// Switch makes this step a choice: the case named by a reference's value
// runs, else the default, else nothing.
Switch *SwitchStep `yaml:"switch,omitempty" json:"switch,omitempty"`
}
// SwitchStep runs the steps of the case whose key equals the value On
// references, else the case named default, else nothing.
type SwitchStep struct {
On string `yaml:"on" json:"on"`
Cases map[string][]StepRecord `yaml:"cases" json:"cases"`
}
const switchDefault = "default"
// RetryPolicy is how often a failed step runs again, and how long it waits
// between attempts.
type RetryPolicy struct {
@@ -211,3 +223,12 @@ func shippedYAML() []WorkflowDefinitionEntry {
}
return entries
}
// branches is every list of steps nested in a step: its parallel branches or
// its switch cases.
func (step StepRecord) branches() map[string][]StepRecord {
if step.Switch != nil {
return step.Switch.Cases
}
return step.Parallel
}
@@ -22,13 +22,16 @@ steps:
type: string
description: The rationale, written for the human who filed the request.
required: [fit, reasons]
- type: forge.close-issue
when: "!steps.assess.result.fit"
- type: workflow.finish
when: "!steps.assess.result.fit"
settings:
status: declined
detail: "{{ steps.assess.result.reasons }}"
- id: verdict
switch:
on: steps.assess.result.fit
cases:
"false":
- type: forge.close-issue
- type: workflow.finish
settings:
status: declined
detail: "{{ steps.assess.result.reasons }}"
- id: prd
type: agent.run
settings:
+81 -1
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"maps"
"slices"
"strings"
"sync"
"time"
@@ -27,7 +28,11 @@ func checkStep(step StepRecord, mode task.RepositoryMode, earlier *refScope, reg
if err := checkStepControls(step, earlier); err != nil {
return err
}
if step.Parallel != nil {
if step.Switch != nil {
if err := checkSwitch(step, mode, earlier, registry, inBranch); err != nil {
return err
}
} else if step.Parallel != nil {
if err := checkParallel(step, mode, earlier, registry, inBranch); err != nil {
return err
}
@@ -133,6 +138,45 @@ func checkParallel(step StepRecord, mode task.RepositoryMode, earlier *refScope,
return nil
}
// checkSwitch validates each case like a branch: a case sees the steps before
// the switch and its own earlier steps. Only one case runs, so its steps need
// not be safe to run side by side, and every case's ids are visible after it.
func checkSwitch(step StepRecord, mode task.RepositoryMode, earlier *refScope, registry StepRegistry, inBranch bool) error {
switch {
case step.Type != "" || step.Settings.Kind != 0 || step.Parallel != nil:
return errors.New("a switch step has cases, not a type, settings or parallel branches")
case len(step.Switch.Cases) == 0:
return errors.New("switch needs at least one case")
}
if err := checkReference(strings.TrimSpace(step.Switch.On), earlier); err != nil {
return fmt.Errorf("switch.on: %w", err)
}
declared := map[string]map[string]bool{}
arms := step.Switch.Cases
for _, name := range slices.Sorted(maps.Keys(arms)) {
if name == "" || strings.Contains(name, "/") {
return fmt.Errorf("case %q is empty or contains /", name)
}
if len(arms[name]) == 0 {
return fmt.Errorf("case %q has no steps", name)
}
seen := earlier.clone()
for i, caseStep := range arms[name] {
if _, twice := declared[caseStep.ID]; twice && caseStep.ID != "" {
return fmt.Errorf("case %q step %d: step id %q is declared twice", name, i+1, caseStep.ID)
}
if err := checkStep(caseStep, mode, seen, registry, inBranch); err != nil {
return fmt.Errorf("case %q step %d: %w", name, i+1, err)
}
if caseStep.ID != "" {
declared[caseStep.ID] = resultFields(caseStep)
}
}
}
maps.Copy(earlier.steps, declared)
return nil
}
// parallelSafe reports whether a step may run beside others in one worktree.
func parallelSafe(step StepRecord) bool {
switch step.Type {
@@ -170,6 +214,9 @@ func Compile(definition YAMLDefinition, registry StepRegistry) (Workflow, error)
}
func compileStep(step StepRecord, registry StepRegistry) (Stage, error) {
if step.Switch != nil {
return compileSwitch(step, registry)
}
if step.Parallel != nil {
return compileParallel(step, registry)
}
@@ -198,6 +245,8 @@ func (step StepRecord) StageName() string {
return step.ID
case step.Parallel != nil:
return "parallel"
case step.Switch != nil:
return "switch"
}
return step.Type
}
@@ -304,6 +353,37 @@ func compileParallel(step StepRecord, registry StepRegistry) (Stage, error) {
}), nil
}
// compileSwitch runs the matching case in the run's own context, recording
// its steps under the case name as a parallel branch records its own.
func compileSwitch(step StepRecord, registry StepRegistry) (Stage, error) {
arms := map[string][]Stage{}
for name, steps := range step.Switch.Cases {
for _, caseStep := range steps {
stage, err := compileStep(caseStep, registry)
if err != nil {
return Stage{}, fmt.Errorf("case %q: %w", name, err)
}
arms[name] = append(arms[name], stage)
}
}
on := strings.Split(strings.TrimSpace(step.Switch.On), ".")
return wrapStep(step, func(ctx context.Context, tc *TaskContext) error {
name := stringify(lookup(referenceScope(tc), on))
stages, ok := arms[name]
if !ok {
name, stages = switchDefault, arms[switchDefault]
}
tc.Log.Info("switch case chosen", "step", step.StageName(), "value", name)
if stages == nil {
return nil
}
parent := tc.workflowBranch
tc.workflowBranch = joinStepPath(parent, name)
defer func() { tc.workflowBranch = parent }()
return runBranch(ctx, tc, stages)
}), nil
}
func runBranch(ctx context.Context, tc *TaskContext, stages []Stage) error {
for _, stage := range stages {
parentID := tc.StepID
@@ -3,9 +3,12 @@ package workflow
import (
"context"
"errors"
"fmt"
"log/slog"
"testing"
"gopkg.in/yaml.v3"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/taskstate"
@@ -100,3 +103,48 @@ func TestRunBranchRecordsChildSteps(t *testing.T) {
})
}
}
// TestSwitchRunsTheMatchingCase pins the switch contract: the case keyed by
// the referenced value runs, else the default case, else nothing, and its steps
// record under the case name.
func TestSwitchRunsTheMatchingCase(t *testing.T) {
src := `id: route
steps:
- switch:
on: task.title
cases:
bug: [{id: fix, type: mark}]
"true": [{id: yes, type: mark}]
%s`
tests := []struct {
name, title, fallback, want string
}{
{name: "a matching case", title: "bug", want: "bug/fix"},
{name: "a boolean-looking key", title: "true", want: "true/yes"},
{name: "no match falls to the default", title: "feature", fallback: " default: [{id: other, type: mark}]", want: "default/other"},
{name: "no match and no default runs nothing", title: "feature"},
}
registry := StepRegistry{"mark": func(yaml.Node) (Stage, error) {
return Stage{Run: func(context.Context, *TaskContext) error { return nil }}, nil
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
wf, err := ParseAndCompile(fmt.Sprintf(src, tt.fallback), registry)
if err != nil {
t.Fatal(err)
}
store := &fakeStepStore{}
tc := &TaskContext{Task: &task.Task{ID: 1, Attempt: 1, Title: tt.title}, Store: store, StepID: 7, Log: slog.Default()}
if err := wf.Stages[0].Run(context.Background(), tc); err != nil {
t.Fatal(err)
}
var got string
if len(store.started) > 0 {
got = store.started[0].Name
}
if got != tt.want {
t.Fatalf("ran %q, want %q", got, tt.want)
}
})
}
}
+3 -2
View File
@@ -449,8 +449,9 @@ func walkSteps(steps []StepRecord, where string, visit func(where string, step S
if err := visit(at, step); err != nil {
return err
}
for _, name := range slices.Sorted(maps.Keys(step.Parallel)) {
if err := walkSteps(step.Parallel[name], fmt.Sprintf("%s branch %q", at, name), visit); err != nil {
branches := step.branches()
for _, name := range slices.Sorted(maps.Keys(branches)) {
if err := walkSteps(branches[name], fmt.Sprintf("%s branch %q", at, name), visit); err != nil {
return err
}
}