feat(eda): add optional playbook action ids and when reference validation

This commit is contained in:
sam committed 2026-09-22 04:36:28 +10:00
1 parent a1302da320
commit 7a7fb9f9bb
4 files changed
+248 -3

No files matched your search

+49 -2
View File
@@ -16,7 +16,10 @@
package expr
import (
"sort"
"cel.dev/cel-go/cel"
celast "cel.dev/cel-go/common/ast"
)
// DefaultCostLimit bounds evaluation of every playbook expression (J5 in the
@@ -79,12 +82,56 @@ func (e *Env) Compile(src string) (*Program, error) {
if err != nil {
return nil, err
}
return &Program{prg: prg}, nil
return &Program{prg: prg, actionIDs: referencedActionIDs(ast)}, nil
}
// referencedActionIDs walks the compiled AST and returns the sorted, de-
// duplicated set of action ids an expression reads through `actions.<id>`.
// `actions` is declared map(string,dyn), so CEL type-checking cannot reject
// an unknown id; the playbook loader compares this set against the ids of
// prior actions to reject unknown references at load (J1 in
// docs/prds/playbook-expression-syntax.md). The map-index form
// (`actions["notify"]`) is a runtime lookup, not a field selection, and is
// intentionally not collected here.
func referencedActionIDs(ast *cel.Ast) []string {
if ast == nil || ast.NativeRep() == nil {
return nil
}
seen := map[string]struct{}{}
visitor := celast.NewExprVisitor(func(e celast.Expr) {
if e.Kind() != celast.SelectKind {
return
}
sel := e.AsSelect()
operand := sel.Operand()
if operand.Kind() != celast.IdentKind || operand.AsIdent() != "actions" {
return
}
seen[sel.FieldName()] = struct{}{}
})
celast.PreOrderVisit(ast.NativeRep().Expr(), visitor)
ids := make([]string, 0, len(seen))
for id := range seen {
ids = append(ids, id)
}
sort.Strings(ids)
return ids
}
// Program is a compiled, cost-limited playbook expression.
type Program struct {
prg cel.Program
prg cel.Program
actionIDs []string
}
// ReferencedActionIDs returns the sorted, de-duplicated action ids the
// expression reads through `actions.<id>`. It is empty when the expression
// reads no prior-action result.
func (p *Program) ReferencedActionIDs() []string {
if p == nil {
return nil
}
return p.actionIDs
}
// Eval evaluates the program against a dispatch-time context. A missing
+46
View File
@@ -1,6 +1,7 @@
package expr
import (
"slices"
"strings"
"testing"
@@ -79,6 +80,51 @@ func TestEvalHasMacroPresence(t *testing.T) {
}
}
// TestReferencedActionIDs: a compiled program exposes the action ids its
// expression reads through actions.<id>, sorted and de-duplicated, so the
// playbook loader can reject references to undeclared prior actions.
func TestReferencedActionIDs(t *testing.T) {
env := NewEnv()
tests := []struct {
name string
src string
want []string
}{
{
name: "single action reference",
src: `actions.notify.result.delivered == true`,
want: []string{"notify"},
},
{
name: "no action reference",
src: `event.priority == 3`,
want: nil,
},
{
name: "multiple references deduped and sorted",
src: `actions.b.result == true || actions.a.result == true || actions.b.result2 == true`,
want: []string{"a", "b"},
},
{
name: "has macro over action",
src: `has(actions.notify.result.delivered)`,
want: []string{"notify"},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
prg, err := env.Compile(tc.src)
if err != nil {
t.Fatalf("Compile: %v", err)
}
got := prg.ReferencedActionIDs()
if !slices.Equal(got, tc.want) {
t.Fatalf("ReferencedActionIDs() = %v, want %v", got, tc.want)
}
})
}
}
// TestEvalActionsContext: prior-action results read via actions.<id>.result.
func TestEvalActionsContext(t *testing.T) {
env := NewEnv()
+69 -1
View File
@@ -18,6 +18,7 @@ import (
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
@@ -68,6 +69,11 @@ type Trigger struct {
// slice, position MUST be "workflow".
type Action struct {
Position string
// ID is an optional stable identifier for this action. When present it
// is the key later actions read this action's result under
// (actions.<id>); the shape is the shared stable-identifier grammar
// (internal/plugin/host.go, internal/domain/workflow/vocabulary.go).
ID string
// Workflow is the name of the workflow definition to dispatch to
// (position: workflow only).
Workflow string
@@ -88,11 +94,62 @@ type rawTrigger struct {
type rawAction struct {
Position string `yaml:"position"`
ID string `yaml:"id"`
Workflow string `yaml:"workflow"`
Kind string `yaml:"kind"`
When string `yaml:"when"`
}
// actionIDPattern is the stable-identifier shape an action id must match when
// declared: a lowercase, dotted/dashed identifier (shared with
// internal/plugin/host.go:21 and internal/domain/workflow/vocabulary.go:19),
// so an id has exactly one spelling and cannot smuggle whitespace or case into
// the vocabulary two processes compare.
var actionIDPattern = regexp.MustCompile(`^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$`)
// validateActionIDs enforces the id shape and uniqueness across a playbook's
// raw actions. An absent id is fine (ids are optional); a declared id must
// match the stable-identifier grammar and may not repeat. Uniqueness is
// unreachable through Load while the one-action boundary holds, so this helper
// is unit-tested directly for the duplicate case.
func validateActionIDs(actions []rawAction) error {
seen := make(map[string]struct{}, len(actions))
for _, a := range actions {
id := a.ID
if id == "" {
continue
}
if !actionIDPattern.MatchString(id) {
return fmt.Errorf("action id %q is not a valid stable identifier (want %s)", id, actionIDPattern.String())
}
if _, dup := seen[id]; dup {
return fmt.Errorf("duplicate action id %q", id)
}
seen[id] = struct{}{}
}
return nil
}
// unknownActionReference returns the first action id a compiled `when` reads
// through actions.<id> that is not declared on any action before index idx.
// The comparison is against earlier actions' declared ids (the general rule
// from J1), so it stays correct when the one-action boundary later relaxes;
// today idx is always 0, so any actions.<id> reference is unknown.
func unknownActionReference(raw []rawAction, idx int, prg *expr.Program) (string, bool) {
declared := make(map[string]struct{}, idx)
for _, prior := range raw[:idx] {
if prior.ID != "" {
declared[prior.ID] = struct{}{}
}
}
for _, id := range prg.ReferencedActionIDs() {
if _, ok := declared[id]; !ok {
return id, true
}
}
return "", false
}
// Load reads every *.yaml/*.yml playbook in dir, validates each against the
// hard boundary (exactly one action, position workflow), and compiles each
// when expression. ANY failure -- malformed YAML, a multi-action playbook, a
@@ -188,9 +245,13 @@ func loadOne(dir, path string, env *expr.Env) (*Playbook, error) {
if strings.TrimSpace(a.Workflow) == "" {
return nil, fmt.Errorf("playbook %s: workflow-kind action must name a workflow", path)
}
if err := validateActionIDs(raw.Actions); err != nil {
return nil, fmt.Errorf("playbook %s: %w", path, err)
}
action := Action{
Position: a.Position,
ID: a.ID,
Workflow: strings.TrimSpace(a.Workflow),
}
if strings.TrimSpace(a.When) != "" {
@@ -198,6 +259,9 @@ func loadOne(dir, path string, env *expr.Env) (*Playbook, error) {
if err != nil {
return nil, fmt.Errorf("playbook %s: when condition: %w", path, err)
}
if id, unknown := unknownActionReference(raw.Actions, 0, prg); unknown {
return nil, fmt.Errorf("playbook %s: when condition references unknown action id %q", path, id)
}
action.When = prg
}
pb.Actions = []Action{action}
@@ -261,6 +325,10 @@ type Decision struct {
PlaybookID string
Version string
Workflow string
// ActionID is the dispatched action's declared id; empty when the action
// declares none. It is the `actions.<id>` key later actions (and the
// dispatch ledger) read this action under.
ActionID string
}
// Dispatch returns the workflow name the first matching playbook selects for
@@ -302,7 +370,7 @@ func (s *Store) Dispatch(input DispatchInput) (Decision, bool) {
continue
}
}
return Decision{PlaybookID: pb.ID, Version: pb.Version, Workflow: a.Workflow}, true
return Decision{PlaybookID: pb.ID, Version: pb.Version, Workflow: a.Workflow, ActionID: a.ID}, true
}
return Decision{}, false
}
@@ -420,6 +420,90 @@ func TestShippedExamplePlaybookLoads(t *testing.T) {
}
}
// TestLoadActionIDDispatches: a valid action id survives load and is
// threaded into the dispatch Decision's ActionID.
func TestLoadActionIDDispatches(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "pb.yaml", `
trigger:
kind: bug
actions:
- position: workflow
workflow: tdd
id: notify
`)
store, err := Load(dir)
if err != nil {
t.Fatalf("Load: %v", err)
}
pb := store.Playbooks[0]
if pb.Actions[0].ID != "notify" {
t.Errorf("action id = %q, want notify", pb.Actions[0].ID)
}
decision, ok := store.Dispatch(DispatchInput{Kind: "bug", Event: map[string]any{}})
if !ok {
t.Fatal("Dispatch matched nothing, want the tdd workflow")
}
if decision.ActionID != "notify" {
t.Errorf("decision ActionID = %q, want notify", decision.ActionID)
}
}
// TestLoadMalformedActionIDFails: an action id outside the stable-identifier
// shape is a reported load failure (the same reject-at-load rule).
func TestLoadMalformedActionIDFails(t *testing.T) {
for _, id := range []string{"Notify", "foo bar", "1st", "-dash", "trailing-", "a..b"} {
t.Run(id, func(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "pb.yaml", "\ntrigger:\n kind: bug\nactions:\n - position: workflow\n workflow: tdd\n id: "+id+"\n")
_, err := Load(dir)
if err == nil {
t.Fatalf("Load(id %q) = nil, want load failure", id)
}
})
}
}
// TestValidateActionIDs: the shape/uniqueness helper is the load-boundary's
// id gate, unit-tested directly because the one-action boundary makes
// duplicates unreachable through Load today.
func TestValidateActionIDs(t *testing.T) {
if err := validateActionIDs([]rawAction{{ID: "notify"}, {ID: "notify"}}); err == nil {
t.Fatal("validateActionIDs(duplicate) = nil, want error")
}
if err := validateActionIDs([]rawAction{{ID: "notify"}, {ID: "build"}}); err != nil {
t.Fatalf("validateActionIDs(distinct) = %v, want nil", err)
}
if err := validateActionIDs([]rawAction{{ID: ""}, {ID: "build"}}); err != nil {
t.Fatalf("validateActionIDs(optional empty id) = %v, want nil", err)
}
}
// TestLoadWhenReferencesUnknownActionIDFails: a when reading actions.<id>
// with no prior action declaring that id is a load failure naming the
// playbook path and the id -- never a runtime miss.
func TestLoadWhenReferencesUnknownActionIDFails(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "pb.yaml", `
trigger:
kind: bug
actions:
- position: workflow
workflow: tdd
when: actions.notify.result.delivered == true
`)
_, err := Load(dir)
if err == nil {
t.Fatal("Load(when referencing undeclared action id) = nil, want load failure")
}
if !strings.Contains(err.Error(), "pb.yaml") {
t.Errorf("Load error = %q, want the playbook path named", err.Error())
}
if !strings.Contains(err.Error(), "notify") {
t.Errorf("Load error = %q, want the unknown id named", err.Error())
}
}
// TestDispatchNilStoreMatchesNothing: a nil store is the state a composition
// root is in before the playbook load runs, and callers hold it through an
// interface where a typed nil is not a nil interface.