feat(eda): evaluate action args as CEL expressions (J2)

This commit is contained in:
sam committed 2026-09-22 05:56:26 +10:00
1 parent 3ee06ce137
commit e339c101b9
3 files changed
+377 -30

No files matched your search

+7 -6
View File
@@ -764,12 +764,13 @@ func (b *boot) loadModules(cfg config.Config, log *slog.Logger) error {
}
// loadEDAPlaybooks loads the EDA playbook documents (t2db.15): trigger +
// single workflow-kind action with CEL when conditions. Loaded at startup
// with the same reject-at-load rule -- any malformed playbook,
// multi-action playbook, non-workflow position, or when compile failure
// aborts startup, matching the routing-file load pattern (not
// degrade-and-skip). A nonexistent dir is an empty store. Split out of
// loadWorkflows (t2db.16); pure extraction, same log messages as before.
// single workflow-kind action with CEL when conditions and args values.
// Loaded at startup with the same reject-at-load rule -- any malformed
// playbook, multi-action playbook, non-workflow position, when compile
// failure, or args compile failure aborts startup, matching the routing-file
// load pattern (not degrade-and-skip). A nonexistent dir is an empty store.
// Split out of loadWorkflows (t2db.16); pure extraction, same log messages as
// before.
func (b *boot) loadEDAPlaybooks(cfg config.Config, log *slog.Logger) error {
var err error
b.playbooks, err = playbook.Load(cfg.EDAPlaybookDir)
+112 -24
View File
@@ -1,7 +1,7 @@
// Package playbook is the EDA playbook document type and its event
// coordinator: the rich trigger+actions YAML shape (docs/prds/
// eda-playbook-engine.md) with CEL `when` conditions (open question 1,
// resolved to CEL). This slice is deliberately single-action,
// eda-playbook-engine.md) with CEL `when` conditions and `args` values
// (open question 1, resolved to CEL). This slice is deliberately single-action,
// workflow-position only: multi-action playbooks and Module/Channel/Forge
// action positions remain blocked on the unresolved execution-time gaps
// (mid-run failure semantics, idempotency for non-workflow actions) and are
@@ -79,6 +79,9 @@ type Action struct {
Workflow string
// When is a compiled CEL condition; nil means unconditional.
When *expr.Program
// Args holds the action's compiled CEL args values, keyed by arg name.
// Nil or empty means the action takes no args.
Args map[string]*expr.Program
}
// rawPlaybook is the YAML document shape before compilation.
@@ -93,11 +96,12 @@ 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"`
Position string `yaml:"position"`
ID string `yaml:"id"`
Workflow string `yaml:"workflow"`
Kind string `yaml:"kind"`
When string `yaml:"when"`
Args map[string]string `yaml:"args"`
}
// actionIDPattern is the stable-identifier shape an action id must match when
@@ -152,10 +156,11 @@ func unknownActionReference(raw []rawAction, idx int, ids []string) (string, boo
// 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
// non-workflow position, a when compile error -- fails the whole load: the
// reject-at-load philosophy of the parent design doc. A missing directory is
// an empty store (matching the flat binding loaders' convention).
// when expression and args value. ANY failure -- malformed YAML, a
// multi-action playbook, a non-workflow position, a when compile error, an
// args compile error -- fails the whole load: the reject-at-load philosophy
// of the parent design doc. A missing directory is an empty store (matching
// the flat binding loaders' convention).
func Load(dir string) (*Store, error) {
entries, err := os.ReadDir(dir)
if os.IsNotExist(err) {
@@ -261,29 +266,69 @@ func loadOne(dir, path string, env *expr.Env) (*Playbook, error) {
}
action.When = prg
}
args, err := compileArgs(path, a.Args, env, raw.Actions)
if err != nil {
return nil, err
}
action.Args = args
pb.Actions = []Action{action}
return pb, nil
}
// compileWhen compiles a raw `when` expression and validates its action
// references against the actions declared before it. It returns the compiled
// program so loadOne can attach it to the action, or the same error loadOne
// previously produced for a compile failure, an unresolvable `actions`
// context root, or a reference to an unknown action id.
// references against the actions declared before it. The wording of the
// returned errors is the loader's existing contract, preserved verbatim by
// passing the `when condition` field label to compileExpr.
func compileWhen(path, when string, env *expr.Env, prior []rawAction) (*expr.Program, error) {
prg, err := env.Compile(strings.TrimSpace(when))
return compileExpr(path, "when condition", when, env, prior)
}
// compileArgs compiles every args value as a CEL expression at load, keyed by
// arg name. J2 has no literal/expression split: the YAML scalar text IS the
// CEL source, so a string literal is quoted inside YAML and a number or
// context read is written as CEL. Each program goes through the same
// compile/reference validation as `when`, with the field label naming the
// offending args key.
func compileArgs(path string, raw map[string]string, env *expr.Env, prior []rawAction) (map[string]*expr.Program, error) {
if len(raw) == 0 {
return nil, nil
}
keys := make([]string, 0, len(raw))
for key := range raw {
keys = append(keys, key)
}
sort.Strings(keys)
args := make(map[string]*expr.Program, len(raw))
for _, key := range keys {
prg, err := compileExpr(path, fmt.Sprintf("args[%q]", key), raw[key], env, prior)
if err != nil {
return nil, err
}
args[key] = prg
}
return args, nil
}
// compileExpr compiles one playbook expression and applies the two load-time
// reference checks: every `actions` read must be statically resolvable to a
// prior action id, and every resolved id must be declared on an earlier
// action. field is the human-readable expression location used in errors
// (`when condition` or `args["name"]`), so a failure names the playbook path
// and the offending expression.
func compileExpr(path, field, src string, env *expr.Env, prior []rawAction) (*expr.Program, error) {
prg, err := env.Compile(strings.TrimSpace(src))
if err != nil {
return nil, fmt.Errorf("playbook %s: when condition: %w", path, err)
return nil, fmt.Errorf("playbook %s: %s: %w", path, field, err)
}
ids, resolvable := prg.ActionReferences()
if !resolvable {
return nil, fmt.Errorf(
"playbook %s: when condition contains an `actions` reference that cannot be statically resolved to an action id (the `actions` context root must be read as a prior action id)",
path,
"playbook %s: %s contains an `actions` reference that cannot be statically resolved to an action id (the `actions` context root must be read as a prior action id)",
path, field,
)
}
if id, unknown := unknownActionReference(prior, 0, ids); unknown {
return nil, fmt.Errorf("playbook %s: when condition references unknown action id %q", path, id)
return nil, fmt.Errorf("playbook %s: %s references unknown action id %q", path, field, id)
}
return prg, nil
}
@@ -376,16 +421,14 @@ func (s *Store) Dispatch(input DispatchInput) (Decision, bool) {
if s == nil {
return Decision{}, false
}
ctx := evalContext(input)
for _, pb := range s.Playbooks {
if !pb.Match(input) {
continue
}
a := pb.Actions[0]
if a.When != nil {
val, err := s.exprEnv.Eval(a.When, expr.Context{
Event: input.Event,
Actions: map[string]map[string]any{},
})
val, err := s.exprEnv.Eval(a.When, ctx)
if err != nil {
// J3: evaluation error -> false (skip), caller logs.
continue
@@ -399,3 +442,48 @@ func (s *Store) Dispatch(input DispatchInput) (Decision, bool) {
}
return Decision{}, false
}
// evalContext is the single evaluation context every CEL expression reads at
// dispatch time. `when` and `args` are both CEL expressions evaluated against
// this one context (J2), so the two can never observe different data.
func evalContext(input DispatchInput) expr.Context {
return expr.Context{
Event: input.Event,
Actions: map[string]map[string]any{},
}
}
// EvalArgs evaluates a compiled action's args against the dispatch context,
// returning the resulting name->value map. No shipped position consumes args
// yet; the consumer arrives with the first side-effecting position (t2db.31).
// An action declaring no args evaluates to an empty map, nil-program entries
// are skipped, and the first evaluation error is returned. Nil-receiver-safe
// for the pre-load composition phase.
//
// Asymmetry with `when`: `when` is a predicate, so an evaluation error is
// false (J3: skip + log); `args` is data, so an evaluation error has no
// meaningful substitute and is returned to the caller to abort the dispatch.
// Ratifying that rule against a real consumer is tracked by archie-core-1h05.
func (s *Store) EvalArgs(a Action, input DispatchInput) (map[string]any, error) {
if s == nil || len(a.Args) == 0 {
return map[string]any{}, nil
}
ctx := evalContext(input)
out := make(map[string]any, len(a.Args))
keys := make([]string, 0, len(a.Args))
for key := range a.Args {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
if a.Args[key] == nil {
continue
}
val, err := s.exprEnv.Eval(a.Args[key], ctx)
if err != nil {
return nil, fmt.Errorf("evaluate args[%q]: %w", key, err)
}
out[key] = val
}
return out, nil
}
@@ -4,6 +4,7 @@ import (
"maps"
"os"
"path/filepath"
"reflect"
"slices"
"strings"
"testing"
@@ -150,6 +151,12 @@ actions:
if err == nil {
t.Fatal("Load(bad when) = nil, want compile failure reported")
}
if !strings.Contains(err.Error(), "pb.yaml") {
t.Errorf("Load error = %q, want the playbook path named", err.Error())
}
if !strings.Contains(err.Error(), "when condition") {
t.Errorf("Load error = %q, want the `when condition` field label named", err.Error())
}
}
// TestLoadEmptyTriggerIsLoadFailure: a playbook without a trigger cannot
@@ -558,3 +565,254 @@ func TestDispatchNilStoreMatchesNothing(t *testing.T) {
t.Fatalf("Dispatch = %v, want no match from a nil store", decision)
}
}
// TestLoadActionArgsEvaluates: a workflow action's args values are compiled as
// CEL at load (a quoted string literal, a number literal, and an event read)
// and EvalArgs evaluates them against the dispatch context to the expected
// name->value map.
func TestLoadActionArgsEvaluates(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "pb.yaml", `
trigger:
kind: bug
actions:
- position: workflow
workflow: tdd
args:
message: '"build finished"'
priority: '3'
label: 'event.label'
`)
store, err := Load(dir)
if err != nil {
t.Fatalf("Load: %v", err)
}
pb := store.Playbooks[0]
if len(pb.Actions[0].Args) != 3 {
t.Fatalf("Action.Args = %#v, want 3 compiled programs", pb.Actions[0].Args)
}
for _, key := range []string{"message", "priority", "label"} {
if pb.Actions[0].Args[key] == nil {
t.Errorf("Action.Args[%q] = nil, want a compiled program", key)
}
}
got, err := store.EvalArgs(pb.Actions[0], DispatchInput{
Event: map[string]any{"label": "bug"},
})
if err != nil {
t.Fatalf("EvalArgs: %v", err)
}
want := map[string]any{
"message": "build finished",
"priority": int64(3),
"label": "bug",
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("EvalArgs = %#v, want %#v", got, want)
}
}
// TestLoadActionArgsFailures: every args value is compiled at load and the
// same reject-at-load rule as `when` applies -- a CEL syntax error, an
// undeclared root, a reference to an unknown actions.<id>, and an
// unresolvable actions reference all fail the whole load, naming the playbook
// path and the offending args key.
func TestLoadActionArgsFailures(t *testing.T) {
tests := []struct {
name string
doc string
wantSub []string
}{
{
name: "syntax error",
doc: `
trigger:
kind: bug
actions:
- position: workflow
workflow: tdd
args:
message: 'build finished'
`,
wantSub: []string{"pb.yaml", `args["message"]`},
},
{
name: "undeclared root",
doc: `
trigger:
kind: bug
actions:
- position: workflow
workflow: tdd
args:
label: 'foo.bar == 1'
`,
wantSub: []string{"pb.yaml", `args["label"]`, "foo"},
},
{
name: "unknown action id",
doc: `
trigger:
kind: bug
actions:
- position: workflow
workflow: tdd
args:
label: 'actions.notify.result.x == true'
`,
wantSub: []string{"pb.yaml", `args["label"]`, "notify"},
},
{
name: "unresolvable actions reference",
doc: `
trigger:
kind: bug
actions:
- position: workflow
workflow: tdd
args:
label: 'actions[event.kind].result.x == true'
`,
wantSub: []string{"pb.yaml", `args["label"]`},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "pb.yaml", tc.doc)
_, err := Load(dir)
if err == nil {
t.Fatal("Load = nil, want load failure")
}
for _, want := range tc.wantSub {
if !strings.Contains(err.Error(), want) {
t.Errorf("Load error = %q, want it to contain %q", err.Error(), want)
}
}
})
}
}
// TestCompileArgsReportsFirstKeyDeterministically: ranging a Go map would
// report a random offending key when more than one args value is invalid; the
// loader must report the alphabetically-first key every time.
func TestCompileArgsReportsFirstKeyDeterministically(t *testing.T) {
env := expr.NewEnv()
raw := map[string]string{
"z.bad": "event.missing ==",
"a.bad": "event.missing ==",
}
for range 64 {
_, err := compileArgs("pb.yaml", raw, env, nil)
if err == nil {
t.Fatal("compileArgs = nil, want error")
}
if !strings.Contains(err.Error(), `args["a.bad"]`) {
t.Fatalf("compileArgs error = %q, want the alphabetically-first key args[%q]", err.Error(), "a.bad")
}
if strings.Contains(err.Error(), `args["z.bad"]`) {
t.Fatalf("compileArgs error = %q, must name the alphabetically-first key, not %q", err.Error(), "z.bad")
}
}
}
// TestEvalArgsMissingEventFieldReturnsError: evaluating an args value that
// reads a missing event field returns an error (never a panic).
func TestEvalArgsMissingEventFieldReturnsError(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "pb.yaml", `
trigger:
kind: bug
actions:
- position: workflow
workflow: tdd
args:
label: 'event.missing'
`)
store, err := Load(dir)
if err != nil {
t.Fatalf("Load: %v", err)
}
_, err = store.EvalArgs(store.Playbooks[0].Actions[0], DispatchInput{Event: map[string]any{}})
if err == nil {
t.Fatal("EvalArgs(missing event field) = nil error, want error (not panic)")
}
}
// TestEvalArgsNoArgsReturnsEmptyMap: an action that declares no args
// evaluates to an empty map and no error.
func TestEvalArgsNoArgsReturnsEmptyMap(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "pb.yaml", `
trigger:
kind: bug
actions:
- position: workflow
workflow: tdd
`)
store, err := Load(dir)
if err != nil {
t.Fatalf("Load: %v", err)
}
got, err := store.EvalArgs(store.Playbooks[0].Actions[0], DispatchInput{Event: map[string]any{}})
if err != nil {
t.Fatalf("EvalArgs: %v", err)
}
if !reflect.DeepEqual(got, map[string]any{}) {
t.Fatalf("EvalArgs = %#v, want a non-nil empty map", got)
}
}
// TestEvalArgsSkipsNilProgram: a nil entry in the exported Args map is
// expressible and must be skipped like the when path tolerates a nil program,
// not panic inside expr.Eval.
func TestEvalArgsSkipsNilProgram(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "pb.yaml", `
trigger:
kind: bug
actions:
- position: workflow
workflow: tdd
args:
message: '"hello"'
`)
store, err := Load(dir)
if err != nil {
t.Fatalf("Load: %v", err)
}
a := store.Playbooks[0].Actions[0]
a.Args["missing"] = nil
got, err := store.EvalArgs(a, DispatchInput{Event: map[string]any{}})
if err != nil {
t.Fatalf("EvalArgs: %v", err)
}
want := map[string]any{"message": "hello"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("EvalArgs = %#v, want %#v", got, want)
}
}
// TestEvalArgsNilStoreSafe: a nil store (the pre-load composition phase) is
// an empty args map rather than a panic.
func TestEvalArgsNilStoreSafe(t *testing.T) {
// A real compiled program on the action proves the early return is the
// nil-store guard and not the no-args guard: with an empty Action, the
// len(a.Args) == 0 branch would satisfy this test even without the s == nil
// check.
env := expr.NewEnv()
prg, err := env.Compile(`"hello"`)
if err != nil {
t.Fatalf("Compile: %v", err)
}
a := Action{Args: map[string]*expr.Program{"message": prg}}
var store *Store
got, err := store.EvalArgs(a, DispatchInput{Event: map[string]any{}})
if err != nil {
t.Fatalf("EvalArgs(nil store) = %v, want nil error", err)
}
if !reflect.DeepEqual(got, map[string]any{}) {
t.Fatalf("EvalArgs(nil store) = %#v, want empty non-nil map", got)
}
}