Files
archie/internal/daemon/playbook_dispatch_test.go
T
sam eaf29459d7 feat(eda): wire action playbooks through loader and module schemas
Pass 2 of archie-core-nx30. Pass 1 typed each prior action's result in
the CEL env; this pass wires that typing through the loader, module
schemas, and daemon, and removes the now-redundant id classifier.

Loader shape (D2): one playbook is exactly one workflow action
(unchanged) OR one or more module actions; the shapes never mix. Mixed,
unsupported, or zero actions fail the load naming the playbook.
playbook.Load now takes a KindSchemas source (a small interface this
package defines, satisfied by *module.ModuleRegistry) so playbook grows
no module import. Callers: bootstrap.loadEDAPlaybooks passes b.modules;
daemon and playbook tests pass module.New().

Per-playbook env (D3): each action's when and args values compile against
an env built from the PRIOR actions' ids typed by their kinds' Result
structs (expr.NewEnv(DeclaredResult{ID,Type})). event stays dyn. An
undeclared id, a forward reference, or a field the kind's Result lacks is
a compile-time undefined-field error.

Args schema (D4): an args key the kind's Args struct does not define
fails the load. An args VALUE whose compiled type mismatches the field
type is left as a named gap (not cheap without leaking cel-go type kinds
into playbook and handling dyn reads); a wrong-typed value still surfaces
at module invoke, not load.

D1: Store.Dispatch routes workflow playbooks only, so an action playbook
cannot hijack the definition pin. bootstrap.loadEDAPlaybooks logs a
visible Warn (not debug) for each loaded action playbook naming it and
stating it does not execute yet.

D5: ModuleRegistry.Invoke is deliberately schema-agnostic (the stored
invoker is type-erased and returns map[string]any). The map-to-Result
marshalling belongs in the coordinator named by the doc, which is the
t2db.31 run path and out of scope here.

Classifier enumeration (E) and verdict, all proven for a typed action
playbook via CEL (expr.NewEnv with a declared log.Result id):

  unknown id                        CEL compile (undefined field)       -> delete unknownActionReference
  literal map index actions["x"]    CEL compile (no _[_] overload)      -> covered
  computed index actions[key]       CEL compile (undeclared 'key')      -> covered
  dynamic index actions[event.name] CEL compile (no _[_] overload)      -> covered
  "x" in actions                    CEL compile (no @in overload)       -> covered
  size(actions)                     CEL compile (no size overload)      -> covered
  actions.all(...)                  CEL compile (not a range)           -> covered
  actions == {}                     CEL compile (no _==_ overload)      -> covered
  bare actions                      compiles; KEPT classifier           -> retained resolvable check

unknownActionReference is deleted; actionReferences/ActionReferences are
kept solely for the bare-actions spelling CEL does not reject.
2026-09-22 09:02:33 +10:00

255 lines
8.4 KiB
Go

package daemon
import (
"log/slog"
"os"
"path/filepath"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/domain/eda/module"
"github.com/samcharles93/archie-core/internal/domain/eda/playbook"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/store"
)
// playbookStore loads a single playbook document from a temp directory, so
// these tests exercise the real loader rather than a hand-built store.
func playbookStore(t *testing.T, document string) *playbook.Store {
t.Helper()
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "pb.yaml"), []byte(document), 0o600); err != nil {
t.Fatal(err)
}
loaded, err := playbook.Load(dir, module.New())
if err != nil {
t.Fatalf("load playbook: %v", err)
}
return loaded
}
// routableDefinitions is the definition collection these tests pin against:
// two real ids so a playbook's choice is distinguishable from the choice the
// kind bindings would have made for the same labels.
func routableDefinitions() *workflowDefinitionsStub {
return &workflowDefinitionsStub{
collection: workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{
{ID: "tdd", YAML: "id: tdd\nsteps:\n - type: bootstrap.apply\n"},
{ID: "feasibility", YAML: "id: feasibility\nsteps:\n - type: bootstrap.prepare\n"},
}},
version: 1,
}
}
// forgeTask enqueues a labelled forge-sourced task and returns its row.
func forgeTask(t *testing.T, resources *store.Store, labels string) *workflow.Task {
t.Helper()
if _, err := resources.EnqueueIssue(t.Context(), "acme", "widget", 7, "title", "body", labels, ""); err != nil {
t.Fatal(err)
}
task, err := resources.TaskByIssue(t.Context(), "acme", "widget", 7)
if err != nil {
t.Fatal(err)
}
return task
}
// TestPinWorkflowDefinitionPrefersMatchingPlaybook is the coordinator's
// production wiring: a forge task whose labels match a loaded playbook pins
// the workflow that playbook names, not the one the kind bindings would have
// chosen for the same labels. Bypassing the coordinator pins "tdd" (the
// default binding for kind bug) and fails this test.
func TestPinWorkflowDefinitionPrefersMatchingPlaybook(t *testing.T) {
resources := store.OpenTest(t)
defer resources.Close()
task := forgeTask(t, resources, "bug")
d := &Daemon{
Store: resources,
WorkflowDefinitions: routableDefinitions(),
Log: slog.New(slog.DiscardHandler),
Playbooks: playbookStore(t, `
trigger:
kind: bug
actions:
- position: workflow
workflow: feasibility
`),
}
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
t.Fatal(err)
}
if task.Workflow != "feasibility" {
t.Fatalf("pinned workflow = %q, want feasibility (the playbook's choice, not the kind binding's)", task.Workflow)
}
stored, err := resources.TaskByID(t.Context(), task.ID)
if err != nil {
t.Fatal(err)
}
if stored.Workflow != "feasibility" {
t.Fatalf("persisted workflow = %q, want feasibility", stored.Workflow)
}
}
// TestPinWorkflowDefinitionFallsBackWhenNoPlaybookMatches: the coordinator is
// an additional routing source, not a replacement. A non-matching playbook
// set leaves the existing kind/label bindings in charge.
func TestPinWorkflowDefinitionFallsBackWhenNoPlaybookMatches(t *testing.T) {
resources := store.OpenTest(t)
defer resources.Close()
task := forgeTask(t, resources, "bug")
d := &Daemon{
Store: resources,
WorkflowDefinitions: routableDefinitions(),
Log: slog.New(slog.DiscardHandler),
Playbooks: playbookStore(t, `
trigger:
kind: bootstrap
actions:
- position: workflow
workflow: feasibility
`),
}
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
t.Fatal(err)
}
if task.Workflow != "tdd" {
t.Fatalf("pinned workflow = %q, want tdd (kind binding for bug)", task.Workflow)
}
}
// TestPinWorkflowDefinitionPlaybookWorkflowMustExist: an operator who binds a
// trigger to a workflow that is not defined gets a reported failure, the same
// shape ResolveWorkflowID gives a task pre-assigned an undefined workflow.
// Silently running the kind binding's choice instead would run the wrong
// workflow under a rule the operator wrote.
func TestPinWorkflowDefinitionPlaybookWorkflowMustExist(t *testing.T) {
resources := store.OpenTest(t)
defer resources.Close()
task := forgeTask(t, resources, "bug")
d := &Daemon{
Store: resources,
WorkflowDefinitions: routableDefinitions(),
Log: slog.New(slog.DiscardHandler),
Playbooks: playbookStore(t, `
trigger:
kind: bug
actions:
- position: workflow
workflow: nonesuch
`),
}
err := d.pinWorkflowDefinition(t.Context(), task)
if err == nil {
t.Fatal("pin succeeded, want an error naming the undefined workflow")
}
if !strings.Contains(err.Error(), "nonesuch") || !strings.Contains(err.Error(), "pb.yaml") {
t.Fatalf("error = %v, want it to name both the workflow and the playbook", err)
}
}
// TestPinWorkflowDefinitionPreAssignedWorkflowBeatsPlaybook: a task carrying
// an explicit workflow is the waiting_human -> approved requeue handoff. That
// assignment is a decision already made about this task and must not be
// re-routed by a playbook trigger that still matches its labels.
func TestPinWorkflowDefinitionPreAssignedWorkflowBeatsPlaybook(t *testing.T) {
resources := store.OpenTest(t)
defer resources.Close()
task := forgeTask(t, resources, "bug")
task.Workflow = "tdd"
d := &Daemon{
Store: resources,
WorkflowDefinitions: routableDefinitions(),
Log: slog.New(slog.DiscardHandler),
Playbooks: playbookStore(t, `
trigger:
kind: bug
actions:
- position: workflow
workflow: feasibility
`),
}
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
t.Fatal(err)
}
if task.Workflow != "tdd" {
t.Fatalf("pinned workflow = %q, want the pre-assigned tdd", task.Workflow)
}
}
// TestPinWorkflowDefinitionEvaluatesConditionAgainstIntakeEvent: a `when`
// condition reads the event surface the daemon really builds from the task
// row. This is the field-name contract between playbookInput and every
// operator-written condition, including the shipped example's -- a rename on
// either side makes conditions silently evaluate false, which this catches.
func TestPinWorkflowDefinitionEvaluatesConditionAgainstIntakeEvent(t *testing.T) {
document := `
trigger:
kind: bug
actions:
- position: workflow
workflow: feasibility
when: '"regression" in event.labels && event.repo == "widget"'
`
for _, tc := range []struct {
name string
labels string
want string
}{
{name: "condition true selects the playbook's workflow", labels: "bug,regression", want: "feasibility"},
{name: "condition false leaves the kind binding in charge", labels: "bug", want: "tdd"},
} {
t.Run(tc.name, func(t *testing.T) {
resources := store.OpenTest(t)
defer resources.Close()
task := forgeTask(t, resources, tc.labels)
d := &Daemon{
Store: resources,
WorkflowDefinitions: routableDefinitions(),
Log: slog.New(slog.DiscardHandler),
Playbooks: playbookStore(t, document),
}
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
t.Fatal(err)
}
if task.Workflow != tc.want {
t.Fatalf("pinned workflow = %q, want %q", task.Workflow, tc.want)
}
})
}
}
// TestPinWorkflowDefinitionTriggersOnInstanceDefinedLabel: the trigger's kind
// axis is the closed workintake vocabulary (it addresses the task subjects),
// so the label axis is what an instance defines for itself. A label no kind
// recognises still triggers a playbook, which is the only way an operator can
// bind a workflow to their own taxonomy without a code change.
func TestPinWorkflowDefinitionTriggersOnInstanceDefinedLabel(t *testing.T) {
resources := store.OpenTest(t)
defer resources.Close()
task := forgeTask(t, resources, "ops::security-review,needs-triage")
d := &Daemon{
Store: resources,
WorkflowDefinitions: routableDefinitions(),
Log: slog.New(slog.DiscardHandler),
Playbooks: playbookStore(t, `
trigger:
labels:
- ops::security-review
actions:
- position: workflow
workflow: feasibility
`),
}
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
t.Fatal(err)
}
if task.Workflow != "feasibility" {
t.Fatalf("pinned workflow = %q, want feasibility (triggered by an instance-defined label)", task.Workflow)
}
}