feat(eda): wire the playbook coordinator into production workflow selection

A loaded playbook now decides a real task's workflow. The wiring point is the
daemon's definition pin (Daemon.resolveWorkflowID, consumed by
pinWorkflowFromCollection), not pollNATS/publishTask as the design doc
assumed: routing moved out of the agent process when workflow definitions
became database rows pinned before dispatch, so the pin is the one place a
task's workflow is chosen.

Precedence: an explicit Task.Workflow (the waiting_human -> approved requeue)
still wins, then a matching playbook, then workflow.ResolveWorkflowID's
existing label/kind bindings. A playbook naming an undefined workflow is a
reported failure that parks the task rather than a silent fall-through to the
binding's choice -- the operator bound that trigger deliberately.

Store.Dispatch returns the selected workflow name plus the matching playbook's
id and version, instead of a compiled workflow.Workflow: the production caller
decides against the active definition collection, and the id/version are the
first two components of the resolved gap-2 idempotency key. The playbook
package no longer imports internal/domain/workflow.

The shipped example's `when` read event.priority, a field no intake supplies,
so it could never have fired once wired. Both examples now read the event
surface playbookInput really builds, and label-trigger.yaml documents the axis
an instance defines for itself: trigger.kind is the closed workintake
vocabulary because a kind addresses a NATS subject, while trigger.labels is
free-form and binds an operator's own taxonomy to a workflow.

Module/Channel/Forge positions stay rejected at load; they need the
playbook_dispatches ledger first (archie-core-t2db.24).

Closes archie-core-t2db.23
This commit is contained in:
sam committed 2026-09-21 23:47:06 +10:00
1 parent 5c5a62ae3b
commit 61887fd781
9 files changed
+504 -79

No files matched your search

+1 -1
View File
@@ -21,7 +21,7 @@
# workflow_routing_file = "~/.local/share/archie/workflow-routing.yaml" # kind->workflow rebinding (bug/feature/bootstrap)
# workflow_labels_file = "~/.local/share/archie/workflow-labels.yaml" # arbitrary forge label -> workflow (EDA playbook slice 2)
# playbook_dirs = ["~/.local/share/archie/workflows"] # list of dirs of *.yaml binding files, merged with the two above (slice 3); a key bound twice across sources is a load failure
# eda_playbook_dir = "~/.local/share/archie/eda-playbooks" # rich EDA playbook documents (trigger + CEL gated single workflow action, t2db.15); distinct from playbook_dirs
# eda_playbook_dir = "~/.local/share/archie/eda-playbooks" # rich EDA playbook documents (trigger + CEL gated single workflow action); a matching one decides the task's workflow ahead of the three binding sources above; distinct from playbook_dirs
poll_interval = "60s"
label = "archie"
+34 -8
View File
@@ -926,14 +926,40 @@ are unblocked on the execution-time questions.
**Status 2026-09-03: resolved across t2db.13-15.** The Module position
(registry + log kind, t2db.13), the CEL expression environment
(t2db.14), and the playbook document + event coordinator with
single-action workflow-kind dispatch (t2db.15) are shipped. The
coordinator is NOT yet wired into production task intake
(daemon.go/pollNATS/publishTask) -- that is a follow-up ticket;
production wiring would make a real forge-triggered task flow through
this coordinator instead of only workflow.Route(). The trigger shape
reuses the existing workintake kind/label vocabulary; multi-action and
non-workflow-position playbooks remain rejected at load (hard
boundary, blocked on gap 2, idempotency).
single-action workflow-kind dispatch (t2db.15) are shipped.
**Status 2026-09-21: wired into production intake (t2db.23).** The
coordinator decides a real task's workflow. The wiring point is the
daemon's definition pin (`Daemon.resolveWorkflowID`, consumed by
`pinWorkflowFromCollection` in `internal/daemon/daemon.go`), not
`pollNATS`/`publishTask` as the earlier note assumed: routing moved out
of the agent process when workflow definitions became database rows
pinned before dispatch, so the pin is now the one place a task's
workflow is chosen. Precedence there is explicit `Task.Workflow` (the
waiting_human -> approved requeue) → matching playbook →
`workflow.ResolveWorkflowID`'s label binding → kind binding → triage →
implement. A playbook naming an undefined workflow is a reported
failure that parks the task rather than a silent fall-through to the
binding's choice.
`Store.Dispatch` returns the selected workflow *name* and the matching
playbook's id/version, not a compiled `workflow.Workflow`: the
production caller decides against the active definition collection, and
the returned id/version are the first two components of the gap-2
idempotency key. The playbook package no longer imports
`internal/domain/workflow`.
The `event` surface a `when` condition reads at this point is what the
intake actually knows about the originating issue: `kind`, `labels`,
`owner`, `repo`, `number`, `title`, `body`, `source`
(`playbookInput` in `internal/daemon/daemon.go`).
The trigger shape reuses the existing workintake kind/label vocabulary;
multi-action and non-workflow-position playbooks remain rejected at
load (hard boundary). Module/Channel/Forge action positions therefore
still have no production dispatch path: the resolved gap-2 scheme's
`playbook_dispatches` ledger is design-only and must land before a
side-effecting position can fire.
5. **Monetization boundary.** Sam has flagged this may be commercialized,
and explicitly wants it discerned from other OSS event-driven-automation
tooling. No design decision needed yet, but worth a note if/when
+30 -5
View File
@@ -10,10 +10,35 @@
# Multi-action playbooks and Module/Channel/Forge action positions stay
# blocked on the unresolved execution-time gaps and are rejected at load.
#
# Trigger matching reuses the existing workintake label/kind vocabulary
# (bug/feature/bootstrap, or a label set). The `when` condition is a CEL
# expression over `event` (the triggering event's fields) -- see
# docs/prds/eda-playbook-engine.md, resolved open question 1.
# A trigger matches on either axis, and both are checked when both are given:
#
# kind: the closed workintake routing vocabulary -- bug, feature,
# bootstrap, default. It is closed because a kind also addresses the
# task's NATS subject; anything else is rejected at load. Set it
# when you want the rule to follow archie's own classification.
# labels: any labels you like, including ones no kind recognises
# ("ops::security-review"). All of them must be present on the
# issue. This is the axis an instance defines for itself: it binds
# your own taxonomy to a workflow with no code change. See
# label-trigger.yaml. The `when` condition is a CEL
# expression over `event` -- see docs/prds/eda-playbook-engine.md, resolved
# open question 1.
#
# A matching playbook decides the task's workflow ahead of the kind/label
# binding files, and a workflow it names that is not defined parks the task
# rather than falling back. For a forge-discovered task, `event` carries:
#
# kind routing kind the labels produced (bug/feature/bootstrap/default)
# labels the issue's labels, as a list
# owner repo owner
# repo repo name
# number issue number
# title issue title
# body issue body
# source "forge" or "chat"
#
# Reading a field that is not in that set is an evaluation error, which the
# coordinator treats as the condition being false (the playbook is skipped).
trigger:
kind: bug
@@ -21,4 +46,4 @@ trigger:
actions:
- position: workflow
workflow: tdd
when: event.priority == 3
when: '"regression" in event.labels'
+19
View File
@@ -0,0 +1,19 @@
# Example EDA playbook triggering on an instance-defined label.
#
# The kind axis (bug/feature/bootstrap/default) is archie's own closed
# classification. This file is the other axis: a label set of your own
# choosing, matched as a subset of the issue's labels. Every label listed here
# must be present on the issue for the playbook to fire.
#
# A matching playbook decides the task's workflow ahead of the
# workflow_routing_file, workflow_labels_file and playbook_dirs bindings. The
# workflow it names must be a defined workflow; naming one that is not parks
# the task with a reported error rather than quietly running a different one.
trigger:
labels:
- ops::security-review
actions:
- position: workflow
workflow: feasibility
+1
View File
@@ -1274,6 +1274,7 @@ func (b *boot) buildDaemon() {
KindWorkflows: b.kindWorkflows,
LabelWorkflows: b.labelWorkflows,
WorkflowDefinitions: b.workflowDefinitions,
Playbooks: b.playbooks,
}
if identities, ok := b.stateStore.(identity.Repository); ok {
b.d.IdentityRepository = identities
+64 -1
View File
@@ -20,6 +20,7 @@ import (
"github.com/samcharles93/archie-core/internal/container"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/curator"
"github.com/samcharles93/archie-core/internal/domain/eda/playbook"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
@@ -196,6 +197,16 @@ type Daemon struct {
// bindings the daemon loaded; nil means built-in defaults.
KindWorkflows workflow.KindWorkflows
LabelWorkflows workflow.LabelWorkflows
// Playbooks is the loaded EDA playbook set (trigger + one workflow-kind
// action, internal/domain/eda/playbook). It is consulted before the
// kind/label bindings when a task's workflow definition is pinned: a
// playbook is an operator's explicit rule for one trigger, where the
// bindings are a table of defaults. Nil means no playbooks are loaded and
// routing is exactly the binding behaviour.
Playbooks interface {
Dispatch(playbook.DispatchInput) (playbook.Decision, bool)
}
// WorkflowDefinitions supplies the active database definitions. A task is
// pinned once before dispatch; retries reuse the task's stored YAML.
WorkflowDefinitions interface {
@@ -1482,12 +1493,64 @@ func (d *Daemon) pinWorkflowDefinition(ctx context.Context, task *workflow.Task)
return d.pinWorkflowFromCollection(ctx, task, collection, version)
}
// resolveWorkflowID picks the definition id to pin. A playbook whose trigger
// matches the task decides, ahead of the kind/label bindings; anything else
// falls through to workflow.ResolveWorkflowID unchanged.
//
// A task that already names a workflow is skipped entirely: that assignment is
// the waiting_human -> approved requeue handoff, a decision already made about
// this specific task, and a trigger that still matches its labels must not
// overturn it.
func (d *Daemon) resolveWorkflowID(task *workflow.Task, available map[string]struct{}) (string, error) {
if d.Playbooks == nil || task.Workflow != "" {
return workflow.ResolveWorkflowID(task, available, d.KindWorkflows, d.LabelWorkflows)
}
decision, matched := d.Playbooks.Dispatch(playbookInput(task))
if !matched {
return workflow.ResolveWorkflowID(task, available, d.KindWorkflows, d.LabelWorkflows)
}
if _, defined := available[decision.Workflow]; !defined {
// Reported, not silently downgraded to the binding's choice: the
// operator bound this trigger to a named workflow, and running a
// different one under their rule is worse than parking the task.
return "", fmt.Errorf("playbook %q binds this trigger to workflow %q, which is not defined", decision.PlaybookID, decision.Workflow)
}
d.Log.Info("playbook selected workflow",
"task", task.ID, "playbook", decision.PlaybookID,
"playbook_version", decision.Version, "workflow", decision.Workflow)
return decision.Workflow, nil
}
// playbookInput builds the coordinator's dispatch input from a task row. The
// event surface is what the intake point actually knows about the originating
// issue -- the fields a `when` condition can read; it is deliberately not
// padded with values the daemon would have to invent.
func playbookInput(task *workflow.Task) playbook.DispatchInput {
labels := workintake.SplitLabels(task.Labels)
kind := string(workintake.KindForLabels(labels))
return playbook.DispatchInput{
Labels: labels,
Kind: kind,
TaskID: workintake.TaskEnvelope{Owner: task.Owner, Repo: task.Repo, Number: task.IssueNumber}.IdempotencyKey(),
Event: map[string]any{
"kind": kind,
"labels": labels,
"owner": task.Owner,
"repo": task.Repo,
"number": task.IssueNumber,
"title": task.Title,
"body": task.Body,
"source": task.Source,
},
}
}
func (d *Daemon) pinWorkflowFromCollection(ctx context.Context, task *workflow.Task, collection workflow.WorkflowDefinitionCollection, version int64) error {
available := make(map[string]struct{}, len(collection.Definitions))
for _, definition := range collection.Definitions {
available[definition.ID] = struct{}{}
}
id, err := workflow.ResolveWorkflowID(task, available, d.KindWorkflows, d.LabelWorkflows)
id, err := d.resolveWorkflowID(task, available)
if err != nil {
return err
}
+253
View File
@@ -0,0 +1,253 @@
package daemon
import (
"log/slog"
"os"
"path/filepath"
"strings"
"testing"
"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)
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)
}
}
+36 -22
View File
@@ -7,10 +7,10 @@
// (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.
// This is an ADDITIONAL routing source alongside the flat kind/label binding
// files (t2db.9/.10/.11): the daemon consults a matching playbook before
// those bindings when it pins a task's workflow definition (t2db.23). The
// binding loaders themselves are untouched.
package playbook
import (
@@ -24,7 +24,6 @@ import (
"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"
)
@@ -69,7 +68,7 @@ type Trigger struct {
// slice, position MUST be "workflow".
type Action struct {
Position string
// Workflow is the named workflow.Registry entry to dispatch to
// Workflow is the name of the workflow definition to dispatch to
// (position: workflow only).
Workflow string
// When is a compiled CEL condition; nil means unconditional.
@@ -252,14 +251,38 @@ func (pb *Playbook) Match(input DispatchInput) bool {
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.
// Decision is what the coordinator selected for one event: the workflow a
// matching playbook's action names, plus the provenance of the definition
// that chose it. Version pins the decision to the exact file content active
// when it fired, and both fields are the first two components of the
// per-action idempotency key the resolved gap-2 scheme derives
// (docs/prds/eda-playbook-engine.md, "Idempotency at execution time").
type Decision struct {
PlaybookID string
Version string
Workflow string
}
// Dispatch returns the workflow name the first matching playbook selects for
// the input, and whether any playbook matched. No match means trigger
// mismatch or a when condition evaluating false, and the caller keeps its own
// routing.
//
// The name is returned rather than a compiled workflow because the production
// caller (the daemon's definition pin) decides against the active definition
// collection, not against a compiled registry; whether the named workflow
// exists is that caller's check, in the same place it makes it for every
// other routing source.
//
// 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 {
func (s *Store) Dispatch(input DispatchInput) (Decision, bool) {
// Nil-receiver-safe: a composition root that builds its daemon before the
// playbook load hands over a nil store, and "no playbooks" is the honest
// answer there rather than a panic.
if s == nil {
return Decision{}, false
}
for _, pb := range s.Playbooks {
if !pb.Match(input) {
continue
@@ -279,16 +302,7 @@ func (s *Store) Dispatch(reg workflow.Registry, input DispatchInput) *workflow.W
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 Decision{PlaybookID: pb.ID, Version: pb.Version, Workflow: a.Workflow}, true
}
return nil
return Decision{}, false
}
+66 -42
View File
@@ -1,12 +1,12 @@
package playbook
import (
"maps"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
func writeFile(t *testing.T, dir, name, content string) string {
@@ -21,14 +21,6 @@ func writeFile(t *testing.T, dir, name, content string) string {
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.
@@ -55,17 +47,19 @@ actions:
}
// Match + dispatch: kind bug, priority 3 -> tdd.
reg := registryWith("implement", "tdd", "feasibility")
dispatched := store.Dispatch(reg, DispatchInput{
decision, ok := store.Dispatch(DispatchInput{
Labels: []string{"bug"},
Kind: "bug",
Event: map[string]any{"priority": 3},
})
if dispatched == nil {
t.Fatal("Dispatch = nil, want the tdd workflow")
if !ok {
t.Fatal("Dispatch matched nothing, want the tdd workflow")
}
if dispatched.Name != "tdd" {
t.Errorf("Dispatched workflow = %q, want tdd", dispatched.Name)
if decision.Workflow != "tdd" {
t.Errorf("Dispatched workflow = %q, want tdd", decision.Workflow)
}
if decision.PlaybookID != "pb.yaml" || decision.Version != pb.Version {
t.Errorf("decision provenance = (%q, %q), want (pb.yaml, %q)", decision.PlaybookID, decision.Version, pb.Version)
}
}
@@ -85,13 +79,13 @@ actions:
if err != nil {
t.Fatalf("Load: %v", err)
}
dispatched := store.Dispatch(registryWith("tdd"), DispatchInput{
decision, ok := store.Dispatch(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)
if ok {
t.Fatalf("Dispatch = %v, want no match (condition false -> skip)", decision)
}
}
@@ -186,13 +180,13 @@ actions:
if err != nil {
t.Fatalf("Load: %v", err)
}
dispatched := store.Dispatch(registryWith("tdd"), DispatchInput{
decision, ok := store.Dispatch(DispatchInput{
Labels: []string{"bug"},
Kind: "bug",
Event: map[string]any{},
})
if dispatched != nil {
t.Fatalf("Dispatch = %v, want nil (trigger kind mismatch)", dispatched)
if ok {
t.Fatalf("Dispatch = %v, want no match (trigger kind mismatch)", decision)
}
}
@@ -211,13 +205,13 @@ actions:
if err != nil {
t.Fatalf("Load: %v", err)
}
dispatched := store.Dispatch(registryWith("tdd"), DispatchInput{
decision, ok := store.Dispatch(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)
if !ok || decision.Workflow != "tdd" {
t.Fatalf("Dispatch = %v, want tdd (no when = always match)", decision)
}
}
@@ -353,16 +347,14 @@ actions:
if err != nil {
t.Fatalf("Load: %v", err)
}
reg := registryWith("tdd")
input := DispatchInput{
Labels: []string{"bug"},
Kind: "bug",
TaskID: "archie:samcharles93/archie-core/42",
Event: map[string]any{"priority": 3},
}
dispatched := store.Dispatch(reg, input)
if dispatched == nil {
t.Fatal("Dispatch = nil, want the tdd workflow")
if _, ok := store.Dispatch(input); !ok {
t.Fatal("Dispatch matched nothing, want the tdd workflow")
}
// The input still carries the identity after dispatch; the caller uses it
// to key the ledger.
@@ -380,28 +372,60 @@ func TestShippedExamplePlaybookLoads(t *testing.T) {
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))
byID := map[string]*Playbook{}
for _, pb := range store.Playbooks {
byID[pb.ID] = pb
}
pb, ok := byID["bug-tdd.yaml"]
if !ok {
t.Fatalf("loaded %v, want the bug-tdd example", slices.Sorted(maps.Keys(byID)))
}
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"},
// The label-trigger example is the instance-defined path: a label the kind
// vocabulary does not recognise, bound to a workflow with no code change.
labelled, ok := byID["label-trigger.yaml"]
if !ok {
t.Fatalf("loaded %v, want the label-trigger example", slices.Sorted(maps.Keys(byID)))
}
if labelled.Trigger.Kind != "" || len(labelled.Trigger.Labels) == 0 {
t.Errorf("label-trigger example = %+v, want a labels-only trigger", labelled.Trigger)
}
if got, _ := store.Dispatch(DispatchInput{
Labels: labelled.Trigger.Labels,
Kind: "default",
Event: map[string]any{"labels": labelled.Trigger.Labels},
}); got.Workflow != labelled.Actions[0].Workflow {
t.Errorf("Dispatch(label-trigger) = %q, want %q", got.Workflow, labelled.Actions[0].Workflow)
}
// The example's when reads event.labels, one of the fields the daemon's
// intake really supplies -- so this exercises the shipped condition
// against the production event surface, not a test-only field.
got, ok := store.Dispatch(DispatchInput{
Labels: []string{"bug", "regression"},
Kind: "bug",
Event: map[string]any{"priority": 3},
Event: map[string]any{"kind": "bug", "labels": []string{"bug", "regression"}},
})
if got == nil || got.Name != "tdd" {
if !ok || got.Workflow != "tdd" {
t.Fatalf("Dispatch(example) = %v, want tdd", got)
}
// And skips for a non-matching priority.
if got := store.Dispatch(registryWith("tdd"), DispatchInput{
// And skips when the label the condition names is absent.
if got, ok := store.Dispatch(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)
Event: map[string]any{"kind": "bug", "labels": []string{"bug"}},
}); ok {
t.Fatalf("Dispatch(unlabelled) = %v, want no match (when false)", got)
}
}
// 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.
func TestDispatchNilStoreMatchesNothing(t *testing.T) {
var store *Store
if decision, ok := store.Dispatch(DispatchInput{Labels: []string{"bug"}, Kind: "bug"}); ok {
t.Fatalf("Dispatch = %v, want no match from a nil store", decision)
}
}