feat(eda): playbook document + event coordinator, single-action workflow-kind dispatch
Seventh slice of docs/prds/eda-playbook-engine.md (t2db.15), consuming
t2db.14's expr package: the rich trigger+actions playbook document and
the coordinator that dispatches it.
- internal/domain/eda/playbook: Load(dir) reads *.yaml/*.yml playbook
documents (trigger + exactly one workflow-kind action + optional CEL
when), validating the HARD BOUNDARY at load: a playbook with 2+ actions
or a non-workflow action position is a reported load failure --
multi-action and Module/Channel/Forge actions stay blocked on the
unresolved execution-time gaps. Any malformed YAML, invalid trigger,
missing workflow name, or when compile failure fails the WHOLE load
(reject-at-load, same shape as routing collisions); a missing dir is an
empty store. Trigger reuses the existing workintake kind/label
vocabulary (no second label-matching mechanism). Dispatch matches
trigger, evaluates when (CEL, event context with actions: {} -- no
prior actions in single-action playbooks), and returns the named
workflow from the registry via the same lookup Route() uses -- no
duplicated dispatch logic. when eval error follows the resolved doc's
J3: false, skip, caller logs.
- Store.Dispatch(reg, DispatchInput) is the coordinator entrypoint; input
carries Labels/Kind/Event. Production task intake wiring
(daemon.go/pollNATS/publishTask) is explicitly NOT in this ticket -- a
follow-up; proven end to end via direct tests plus the shipped example
(examples/eda-playbooks/bug-tdd.yaml) loaded and dispatched through the
real path.
- Config: EDAPlaybookDir (eda_playbook_dir), documented as DISTINCT from
PlaybookDirs (flat binding files) -- a reader cannot confuse the two.
- Bootstrap: playbook.Load wired in loadWorkflows, log-and-abort on
failure matching every prior slice; nonexistent dir is an empty store.
- workflow.Route(), workflowForLabels, and the t2db.9-.12 binding loaders
are UNTOUCHED (verified: their full test suites pass, zero regressions).
Also carries small lint cleanups on t2db.13/.14 code flagged by the gate
run: expr Eval no longer type-asserts to ref.Val (Eval returns ref.Val
directly in v0.32.0; cel-go's own Eval wraps evaluation in recover --
verified in source); module decodeLogArgs extracted to clear the nestif
finding. golangci-lint: 0 issues.
Tests (10): single-action round trip, when-false skip, 2-action load
failure, non-workflow position load failure, when compile failure drops
playbook, empty trigger load failure, trigger mismatch skip, no-when
match, one-invalid-file fails whole load, missing dir empty store, plus
the shipped example load+dispatch. task check clean (113/113 UI, exit 0).
This commit is contained in:
1 parent
7e34fcb598
commit
e7afe2da8b
12 files changed
+661
-37
No files matched your search
@@ -32,6 +32,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/daemon"
|
||||
"github.com/samcharles93/archie-core/internal/domain/curator"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/module"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/playbook"
|
||||
domainmemory "github.com/samcharles93/archie-core/internal/domain/memory"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/skillbuild"
|
||||
@@ -92,6 +93,8 @@ type boot struct {
|
||||
|
||||
modules *module.ModuleRegistry
|
||||
|
||||
playbooks *playbook.Store
|
||||
|
||||
st store.TaskStore
|
||||
chatSessionStore gateway.SessionStore
|
||||
|
||||
@@ -702,6 +705,19 @@ func (b *boot) loadWorkflows(ctx context.Context) error {
|
||||
log.Info("module registry built", "dir", cfg.ModuleDir, "kinds", b.modules.Len())
|
||||
}
|
||||
|
||||
// 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.
|
||||
b.playbooks, err = playbook.Load(cfg.EDAPlaybookDir)
|
||||
if err != nil {
|
||||
log.Error("eda playbook load failed", "dir", cfg.EDAPlaybookDir, "err", err)
|
||||
return err
|
||||
}
|
||||
log.Info("eda playbooks loaded", "dir", cfg.EDAPlaybookDir, "playbooks", len(b.playbooks.Playbooks))
|
||||
|
||||
skillsBase := cfg.SkillsDir
|
||||
if skillsBase == "" {
|
||||
skillsBase = cfg.WorkDir
|
||||
|
||||
@@ -458,6 +458,14 @@ type Config struct {
|
||||
// playbook directories are loaded. Repo-scoping of playbook dirs is a
|
||||
// separate, later decision and is not attempted here.
|
||||
PlaybookDirs []string `toml:"playbook_dirs" yaml:"playbook_dirs"`
|
||||
// EDAPlaybookDir is an optional path to a directory of rich EDA playbook
|
||||
// documents (*.yaml/*.yml: trigger + ordered actions with CEL `when`
|
||||
// conditions, dispatched by the event coordinator). This is DISTINCT
|
||||
// from PlaybookDirs, which holds FLAT binding files (kind/label ->
|
||||
// workflow name) consumed by the routing loaders. A playbook here is a
|
||||
// document (one trigger, one action in this slice); a binding file there
|
||||
// is a map of keys. When empty, no EDA playbook documents are loaded.
|
||||
EDAPlaybookDir string `toml:"eda_playbook_dir" yaml:"eda_playbook_dir"`
|
||||
// MaxRetries caps how many times a parked task is retried before
|
||||
// being permanently parked (status "dead"). Defaults to 3.
|
||||
MaxRetries int `toml:"max_retries" yaml:"max_retries"`
|
||||
|
||||
@@ -17,7 +17,6 @@ package expr
|
||||
|
||||
import (
|
||||
"cel.dev/cel-go/cel"
|
||||
"cel.dev/cel-go/common/types/ref"
|
||||
)
|
||||
|
||||
// DefaultCostLimit bounds evaluation of every playbook expression (J5 in the
|
||||
@@ -90,8 +89,10 @@ type Program struct {
|
||||
|
||||
// Eval evaluates the program against a dispatch-time context. A missing
|
||||
// field, a wrong type against a dyn value, or an exceeded cost limit is a
|
||||
// returned error -- CEL evaluation is panic-free, so no recover() wrapper is
|
||||
// needed (verified in the acceptance tests).
|
||||
// returned error. CEL's own evaluation recovers panics internally (verified
|
||||
// in cel-go's program.go: Eval wraps evaluation in recover), and its
|
||||
// returned values implement ref.Val -- unwrapped here to the native Go value
|
||||
// the caller expects.
|
||||
func (e *Env) Eval(prg *Program, ctx Context) (any, error) {
|
||||
data := map[string]any{
|
||||
"event": ctx.Event,
|
||||
@@ -101,11 +102,5 @@ func (e *Env) Eval(prg *Program, ctx Context) (any, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// CEL returns typed wrappers (types.Bool, types.String, ...) that
|
||||
// implement ref.Val. Unwrap to the native Go value the caller expects;
|
||||
// an already-native value passes through unchanged.
|
||||
if rv, ok := v.(ref.Val); ok {
|
||||
return rv.Value(), nil
|
||||
}
|
||||
return v, nil
|
||||
return v.Value(), nil
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"testing"
|
||||
|
||||
"cel.dev/cel-go/cel"
|
||||
"cel.dev/cel-go/common/types/ref"
|
||||
)
|
||||
|
||||
// TestCompileEvalValidBooleanAgainstEvent is the happy path: a boolean
|
||||
@@ -156,10 +155,7 @@ func evalUnderLimit(prg *Program, limit uint64) (any, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rv, ok := v.(ref.Val); ok {
|
||||
return rv.Value(), nil
|
||||
}
|
||||
return v, nil
|
||||
return v.Value(), nil
|
||||
}
|
||||
|
||||
// TestEvalPanicFreeHostileData: a pathological nested map under evaluation
|
||||
|
||||
@@ -147,27 +147,9 @@ func logInvoker(label, src string, k Kind) (invoker, error) {
|
||||
// interface symmetry with future kinds that need cancellation; the log kind
|
||||
// is side-effect-free and does not use it.
|
||||
func runLog(_ context.Context, label string, run func(log.Args) log.Result, rawArgs map[string]any) (map[string]any, error) {
|
||||
var args log.Args
|
||||
if rawArgs != nil {
|
||||
if msg, ok := rawArgs["message"]; ok {
|
||||
s, ok := msg.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("module log: args.message is %T, want string", msg)
|
||||
}
|
||||
args.Message = s
|
||||
}
|
||||
if lvl, ok := rawArgs["level"]; ok {
|
||||
s, ok := lvl.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("module log: args.level is %T, want string", lvl)
|
||||
}
|
||||
args.Level = s
|
||||
}
|
||||
for key := range rawArgs {
|
||||
if key != "message" && key != "level" {
|
||||
return nil, fmt.Errorf("module log: unknown arg %q", key)
|
||||
}
|
||||
}
|
||||
args, err := decodeLogArgs(rawArgs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res, err := yaegiutil.Safe(label, func() (log.Result, error) {
|
||||
return run(args), nil
|
||||
@@ -181,6 +163,36 @@ func runLog(_ context.Context, label string, run func(log.Args) log.Result, rawA
|
||||
}, nil
|
||||
}
|
||||
|
||||
// decodeLogArgs strictly decodes rawArgs into log.Args: a wrong-typed field
|
||||
// or an unknown key is a reported error, never a silent zero-value fill --
|
||||
// the "schema defines the accepted message" rule.
|
||||
func decodeLogArgs(rawArgs map[string]any) (log.Args, error) {
|
||||
var args log.Args
|
||||
if rawArgs == nil {
|
||||
return args, nil
|
||||
}
|
||||
if msg, ok := rawArgs["message"]; ok {
|
||||
s, ok := msg.(string)
|
||||
if !ok {
|
||||
return args, fmt.Errorf("module log: args.message is %T, want string", msg)
|
||||
}
|
||||
args.Message = s
|
||||
}
|
||||
if lvl, ok := rawArgs["level"]; ok {
|
||||
s, ok := lvl.(string)
|
||||
if !ok {
|
||||
return args, fmt.Errorf("module log: args.level is %T, want string", lvl)
|
||||
}
|
||||
args.Level = s
|
||||
}
|
||||
for key := range rawArgs {
|
||||
if key != "message" && key != "level" {
|
||||
return args, fmt.Errorf("module log: unknown arg %q", key)
|
||||
}
|
||||
}
|
||||
return args, nil
|
||||
}
|
||||
|
||||
// Invoke calls the registered kind with rawArgs and returns the marshaled
|
||||
// result. An unregistered kind is a reported error.
|
||||
func (r *ModuleRegistry) Invoke(ctx context.Context, kind string, rawArgs map[string]any) (map[string]any, error) {
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
// 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,
|
||||
// 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
|
||||
// rejected at load -- the hard boundary, not to be relaxed without sign-off.
|
||||
//
|
||||
// This is an ADDITIONAL loading path alongside the flat kind/label binding
|
||||
// files (t2db.9/.10/.11). workflow.Route() and the existing binding loaders
|
||||
// are untouched; migrating Route() onto this mechanism is a separate, later
|
||||
// decision.
|
||||
package playbook
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/expr"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
||||
)
|
||||
|
||||
// Store is the loaded set of playbooks, validated and compiled at load time.
|
||||
type Store struct {
|
||||
Playbooks []*Playbook
|
||||
exprEnv *expr.Env
|
||||
}
|
||||
|
||||
// Playbook is one trigger+actions document.
|
||||
type Playbook struct {
|
||||
Trigger Trigger
|
||||
Actions []Action
|
||||
}
|
||||
|
||||
// Trigger decides which incoming events this playbook matches. It reuses the
|
||||
// existing workintake label/kind vocabulary -- no second label-matching
|
||||
// mechanism is invented here.
|
||||
type Trigger struct {
|
||||
// Kind is the routing kind (bug/feature/bootstrap); empty matches the
|
||||
// default (unlabelled) flow.
|
||||
Kind workintake.Kind
|
||||
// Labels is the closed label set this trigger matches; an empty set
|
||||
// matches any labels.
|
||||
Labels []string
|
||||
}
|
||||
|
||||
// Action is one step in a playbook. Exactly one action per playbook in this
|
||||
// slice, position MUST be "workflow".
|
||||
type Action struct {
|
||||
Position string
|
||||
// Workflow is the named workflow.Registry entry to dispatch to
|
||||
// (position: workflow only).
|
||||
Workflow string
|
||||
// When is a compiled CEL condition; nil means unconditional.
|
||||
When *expr.Program
|
||||
}
|
||||
|
||||
// rawPlaybook is the YAML document shape before compilation.
|
||||
type rawPlaybook struct {
|
||||
Trigger rawTrigger `yaml:"trigger"`
|
||||
Actions []rawAction `yaml:"actions"`
|
||||
}
|
||||
|
||||
type rawTrigger struct {
|
||||
Kind string `yaml:"kind"`
|
||||
Labels []string `yaml:"labels"`
|
||||
}
|
||||
|
||||
type rawAction struct {
|
||||
Position string `yaml:"position"`
|
||||
Workflow string `yaml:"workflow"`
|
||||
Kind string `yaml:"kind"`
|
||||
When string `yaml:"when"`
|
||||
}
|
||||
|
||||
// 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).
|
||||
func Load(dir string) (*Store, error) {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if os.IsNotExist(err) {
|
||||
return &Store{exprEnv: expr.NewEnv()}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read playbook dir %s: %w", dir, err)
|
||||
}
|
||||
|
||||
var names []string
|
||||
for _, e := range entries {
|
||||
if e.IsDir() {
|
||||
continue
|
||||
}
|
||||
if ext := strings.ToLower(filepath.Ext(e.Name())); ext == ".yaml" || ext == ".yml" {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
|
||||
store := &Store{exprEnv: expr.NewEnv()}
|
||||
for _, name := range names {
|
||||
path := filepath.Join(dir, name)
|
||||
pb, err := loadOne(path, store.exprEnv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
store.Playbooks = append(store.Playbooks, pb)
|
||||
}
|
||||
return store, nil
|
||||
}
|
||||
|
||||
// loadOne loads and validates a single playbook file.
|
||||
func loadOne(path string, env *expr.Env) (*Playbook, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read playbook %s: %w", path, err)
|
||||
}
|
||||
var raw rawPlaybook
|
||||
if err := yaml.Unmarshal(data, &raw); err != nil {
|
||||
return nil, fmt.Errorf("parse playbook %s: %w", path, err)
|
||||
}
|
||||
|
||||
pb := &Playbook{
|
||||
Trigger: Trigger{
|
||||
Kind: workintake.Kind(strings.TrimSpace(raw.Trigger.Kind)),
|
||||
Labels: raw.Trigger.Labels,
|
||||
},
|
||||
}
|
||||
|
||||
if pb.Trigger.Kind == "" && len(raw.Trigger.Labels) == 0 {
|
||||
return nil, fmt.Errorf("playbook %s: trigger must declare a kind or labels", path)
|
||||
}
|
||||
if err := pb.Trigger.Kind.Validate(); err != nil {
|
||||
return nil, fmt.Errorf("playbook %s: %w", path, err)
|
||||
}
|
||||
|
||||
// HARD BOUNDARY (t2db.15): exactly one action, position workflow only.
|
||||
if len(raw.Actions) != 1 {
|
||||
return nil, fmt.Errorf(
|
||||
"playbook %s: exactly one action is supported; got %d (multi-action playbooks are blocked on unresolved execution-time gaps)",
|
||||
path, len(raw.Actions),
|
||||
)
|
||||
}
|
||||
a := raw.Actions[0]
|
||||
b := "workflow"
|
||||
if a.Position == "" {
|
||||
// Default position for a single bare workflow name stays workflow for
|
||||
// the smallest-useful case.
|
||||
a.Position = b
|
||||
}
|
||||
if a.Position != b {
|
||||
return nil, fmt.Errorf(
|
||||
"playbook %s: action position %q is not supported; only %q actions ship (Module/Channel/Forge positions are blocked on unresolved execution-time gaps)",
|
||||
path, a.Position, b,
|
||||
)
|
||||
}
|
||||
if strings.TrimSpace(a.Workflow) == "" {
|
||||
return nil, fmt.Errorf("playbook %s: workflow-kind action must name a workflow", path)
|
||||
}
|
||||
|
||||
action := Action{
|
||||
Position: a.Position,
|
||||
Workflow: strings.TrimSpace(a.Workflow),
|
||||
}
|
||||
if strings.TrimSpace(a.When) != "" {
|
||||
prg, err := env.Compile(strings.TrimSpace(a.When))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("playbook %s: when condition: %w", path, err)
|
||||
}
|
||||
action.When = prg
|
||||
}
|
||||
pb.Actions = []Action{action}
|
||||
return pb, nil
|
||||
}
|
||||
|
||||
// DispatchInput is what the coordinator evaluates a playbook against at
|
||||
// dispatch time.
|
||||
type DispatchInput struct {
|
||||
// Labels are the incoming task's labels (comma-split already).
|
||||
Labels []string
|
||||
// Kind is the routing kind the labels produced (workintake.KindForLabels).
|
||||
Kind string
|
||||
// Event is the event payload exposed as `event` in CEL expressions. For
|
||||
// a workflow-kind dispatch this carries the label/kind fields cheaply
|
||||
// available at this point.
|
||||
Event map[string]any
|
||||
}
|
||||
|
||||
// Match reports whether the playbook's trigger matches the input's labels.
|
||||
func (pb *Playbook) Match(input DispatchInput) bool {
|
||||
labels := input.Labels
|
||||
if len(labels) == 0 {
|
||||
labels = []string{}
|
||||
}
|
||||
kind := workintake.Kind(input.Kind)
|
||||
|
||||
if pb.Trigger.Kind != "" && pb.Trigger.Kind != kind {
|
||||
return false
|
||||
}
|
||||
if len(pb.Trigger.Labels) > 0 {
|
||||
// Trigger labels must all be present in the input's labels.
|
||||
inputSet := make(map[string]bool, len(labels))
|
||||
for _, l := range labels {
|
||||
inputSet[strings.TrimSpace(l)] = true
|
||||
}
|
||||
for _, want := range pb.Trigger.Labels {
|
||||
if !inputSet[strings.TrimSpace(want)] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Dispatch returns the workflow to run for the input, or nil if no playbook
|
||||
// matches (trigger mismatch or a when condition evaluating false). It reuses
|
||||
// the named-workflow lookup that workflow.Route() uses -- it does not
|
||||
// duplicate dispatch logic.
|
||||
//
|
||||
// A when evaluation error follows the resolved doc's J3: the condition
|
||||
// evaluates to false and dispatch is skipped (the caller logs).
|
||||
func (s *Store) Dispatch(reg workflow.Registry, input DispatchInput) *workflow.Workflow {
|
||||
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{},
|
||||
})
|
||||
if err != nil {
|
||||
// J3: evaluation error -> false (skip), caller logs.
|
||||
continue
|
||||
}
|
||||
b, ok := val.(bool)
|
||||
if !ok || !b {
|
||||
continue
|
||||
}
|
||||
}
|
||||
// Reuse the same named-workflow lookup Route() uses: this is the
|
||||
// workflow.Registry map access, not a second dispatch path.
|
||||
if wf, ok := reg[a.Workflow]; ok {
|
||||
// Return a copy to keep the registry immutable from callers.
|
||||
wfCopy := wf
|
||||
return &wfCopy
|
||||
}
|
||||
// Requested workflow unavailable: reported as nil (the caller's
|
||||
// Route()-equivalent handles the missing-workflow failure shape).
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
package playbook
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
)
|
||||
|
||||
func writeFile(t *testing.T, dir, name, content string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(dir, name)
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
|
||||
t.Fatalf("write %s: %v", path, err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func registryWith(workflows ...string) workflow.Registry {
|
||||
reg := workflow.Registry{}
|
||||
for _, name := range workflows {
|
||||
reg[name] = workflow.Workflow{Name: name, Stages: []workflow.Stage{}}
|
||||
}
|
||||
return reg
|
||||
}
|
||||
|
||||
// TestLoadSingleWorkflowActionRoundTrip: a playbook with trigger + one
|
||||
// workflow-kind action + optional when loads and dispatches to the correct
|
||||
// registered workflow when trigger+when match.
|
||||
func TestLoadSingleWorkflowActionRoundTrip(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: workflow
|
||||
workflow: tdd
|
||||
when: event.priority == 3
|
||||
`)
|
||||
store, err := Load(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if len(store.Playbooks) != 1 {
|
||||
t.Fatalf("loaded %d playbooks, want 1", len(store.Playbooks))
|
||||
}
|
||||
pb := store.Playbooks[0]
|
||||
if pb.Actions[0].Position != "workflow" {
|
||||
t.Errorf("position = %q, want workflow", pb.Actions[0].Position)
|
||||
}
|
||||
|
||||
// Match + dispatch: kind bug, priority 3 -> tdd.
|
||||
reg := registryWith("implement", "tdd", "feasibility")
|
||||
dispatched := store.Dispatch(reg, DispatchInput{
|
||||
Labels: []string{"bug"},
|
||||
Kind: "bug",
|
||||
Event: map[string]any{"priority": 3},
|
||||
})
|
||||
if dispatched == nil {
|
||||
t.Fatal("Dispatch = nil, want the tdd workflow")
|
||||
}
|
||||
if dispatched.Name != "tdd" {
|
||||
t.Errorf("Dispatched workflow = %q, want tdd", dispatched.Name)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDispatchConditionFalseSkips: a when that compiles but evaluates false
|
||||
// at dispatch correctly skips dispatch (nil returned, not silently ignored).
|
||||
func TestDispatchConditionFalseSkips(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: workflow
|
||||
workflow: tdd
|
||||
when: event.priority == 5
|
||||
`)
|
||||
store, err := Load(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
dispatched := store.Dispatch(registryWith("tdd"), DispatchInput{
|
||||
Labels: []string{"bug"},
|
||||
Kind: "bug",
|
||||
Event: map[string]any{"priority": 3},
|
||||
})
|
||||
if dispatched != nil {
|
||||
t.Fatalf("Dispatch = %v, want nil (condition false -> skip)", dispatched)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadTwoActionsIsLoadFailure: the hard boundary -- a playbook declaring
|
||||
// 2+ actions is a reported load failure.
|
||||
func TestLoadTwoActionsIsLoadFailure(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: workflow
|
||||
workflow: tdd
|
||||
- position: workflow
|
||||
workflow: implement
|
||||
`)
|
||||
_, err := Load(dir)
|
||||
if err == nil {
|
||||
t.Fatal("Load(2 actions) = nil, want load failure")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "exactly one action") {
|
||||
t.Errorf("Load error = %q, want the one-action rule named", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadNonWorkflowPositionIsLoadFailure: a playbook with a non-workflow
|
||||
// action position is a reported load failure.
|
||||
func TestLoadNonWorkflowPositionIsLoadFailure(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: module
|
||||
kind: log
|
||||
`)
|
||||
_, err := Load(dir)
|
||||
if err == nil {
|
||||
t.Fatal("Load(module action) = nil, want load failure")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "workflow") {
|
||||
t.Errorf("Load error = %q, want the position restriction named", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadWhenCompileFailureDropsPlaybook: a when compile failure at load is
|
||||
// reported and the playbook is dropped (same reject-at-load shape as the
|
||||
// collision rule).
|
||||
func TestLoadWhenCompileFailureDropsPlaybook(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: workflow
|
||||
workflow: tdd
|
||||
when: event.label ==
|
||||
`)
|
||||
_, err := Load(dir)
|
||||
if err == nil {
|
||||
t.Fatal("Load(bad when) = nil, want compile failure reported")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadEmptyTriggerIsLoadFailure: a playbook without a trigger cannot
|
||||
// match anything -- rejected at load.
|
||||
func TestLoadEmptyTriggerIsLoadFailure(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", `
|
||||
actions:
|
||||
- position: workflow
|
||||
workflow: tdd
|
||||
`)
|
||||
_, err := Load(dir)
|
||||
if err == nil {
|
||||
t.Fatal("Load(no trigger) = nil, want load failure")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDispatchTriggerMismatchSkips: a playbook whose trigger does not match
|
||||
// the incoming labels does not dispatch.
|
||||
func TestDispatchTriggerMismatchSkips(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", `
|
||||
trigger:
|
||||
kind: feature
|
||||
actions:
|
||||
- position: workflow
|
||||
workflow: tdd
|
||||
`)
|
||||
store, err := Load(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
dispatched := store.Dispatch(registryWith("tdd"), DispatchInput{
|
||||
Labels: []string{"bug"},
|
||||
Kind: "bug",
|
||||
Event: map[string]any{},
|
||||
})
|
||||
if dispatched != nil {
|
||||
t.Fatalf("Dispatch = %v, want nil (trigger kind mismatch)", dispatched)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDispatchNoWhenMatchesOnTriggerAlone: without a when, trigger match is
|
||||
// sufficient to dispatch.
|
||||
func TestDispatchNoWhenMatchesOnTriggerAlone(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)
|
||||
}
|
||||
dispatched := store.Dispatch(registryWith("tdd"), DispatchInput{
|
||||
Labels: []string{"bug"},
|
||||
Kind: "bug",
|
||||
Event: map[string]any{},
|
||||
})
|
||||
if dispatched == nil || dispatched.Name != "tdd" {
|
||||
t.Fatalf("Dispatch = %v, want tdd (no when = always match)", dispatched)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadOneInvalidFileFailsWholeLoad: the reject-at-load rule is store-
|
||||
// level -- one malformed playbook in a directory fails the entire load, so
|
||||
// a partially-valid set never starts (same shape as a routing collision).
|
||||
func TestLoadOneInvalidFileFailsWholeLoad(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "good.yaml", `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: workflow
|
||||
workflow: tdd
|
||||
`)
|
||||
writeFile(t, dir, "bad.yaml", `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: workflow
|
||||
workflow: tdd
|
||||
- position: workflow
|
||||
workflow: implement
|
||||
`)
|
||||
_, err := Load(dir)
|
||||
if err == nil {
|
||||
t.Fatal("Load(dir with one bad playbook) = nil, want whole-load failure")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadMissingDirIsEmptyStore: a nonexistent directory is an empty store
|
||||
// (no playbooks), matching the flat binding loaders' convention.
|
||||
func TestLoadMissingDirIsEmptyStore(t *testing.T) {
|
||||
store, err := Load(filepath.Join(t.TempDir(), "does-not-exist"))
|
||||
if err != nil {
|
||||
t.Fatalf("Load(missing dir) = %v, want nil", err)
|
||||
}
|
||||
if len(store.Playbooks) != 0 {
|
||||
t.Fatalf("loaded %d playbooks, want 0", len(store.Playbooks))
|
||||
}
|
||||
}
|
||||
|
||||
// TestShippedExamplePlaybookLoads verifies the operator-facing example
|
||||
// (examples/eda-playbooks/bug-tdd.yaml) loads through the real loader --
|
||||
// the proof the shipped shape works, not just test fixtures.
|
||||
func TestShippedExamplePlaybookLoads(t *testing.T) {
|
||||
dir := filepath.Join("..", "..", "..", "..", "examples", "eda-playbooks")
|
||||
store, err := Load(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("Load(shipped example): %v", err)
|
||||
}
|
||||
if len(store.Playbooks) != 1 {
|
||||
t.Fatalf("loaded %d playbooks, want 1", len(store.Playbooks))
|
||||
}
|
||||
pb := store.Playbooks[0]
|
||||
if pb.Actions[0].Workflow != "tdd" {
|
||||
t.Errorf("example workflow = %q, want tdd", pb.Actions[0].Workflow)
|
||||
}
|
||||
// The example's when (event.priority == 3) dispatches for priority 3.
|
||||
got := store.Dispatch(registryWith("tdd"), DispatchInput{
|
||||
Labels: []string{"bug"},
|
||||
Kind: "bug",
|
||||
Event: map[string]any{"priority": 3},
|
||||
})
|
||||
if got == nil || got.Name != "tdd" {
|
||||
t.Fatalf("Dispatch(example) = %v, want tdd", got)
|
||||
}
|
||||
// And skips for a non-matching priority.
|
||||
if got := store.Dispatch(registryWith("tdd"), DispatchInput{
|
||||
Labels: []string{"bug"},
|
||||
Kind: "bug",
|
||||
Event: map[string]any{"priority": 5},
|
||||
}); got != nil {
|
||||
t.Fatalf("Dispatch(priority 5) = %v, want nil (when false)", got)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user