feat(workflow): issue routing is a control-plane setting edited in the dashboard (#1959)

Label to workflow rules and a default workflow are the intake-routes
resource: ordered, case-insensitive, first rule wins, seeded with bug to
tdd, feature to feasibility, default triage. A write naming an undefined
workflow or an empty label is refused. The daemon reads it through the
workflow definitions client when pinning a task and at intake.

The kind indirection only carried this routing, so it is removed: the
per-kind NATS subjects (every consumer already bound archie.task.>) are
one subject, the envelope and playbook triggers lose their kind, and
x-intake-routes is dropped. The dashboard gets an Issue routing page
under Automation; the trigger card reads the same setting.
This commit is contained in:
sam committed 2026-11-13 20:28:52 +11:00
1 parent ca4b039cb4
commit 41f44c43a1
28 files changed
+395 -234

No files matched your search

+5 -3
View File
@@ -314,8 +314,10 @@ expressions that limit which files the rule applies to.
## What starts a workflow ## What starts a workflow
- **Issues**, by label: `bug` runs `tdd`, `feature` runs `feasibility`, anything - **Issues**, by label: the Issue routing setting lists label to workflow rules
else runs `triage`, which classifies it and hands off. (first match wins) and a default for the rest. It starts as `bug` runs
`tdd`, `feature` runs `feasibility`, anything else runs `triage`, which
classifies it and hands off.
- **Event bindings**: a webhook source mapped onto a workflow and its inputs - **Event bindings**: a webhook source mapped onto a workflow and its inputs
(Events page). (Events page).
- **Schedules**: each firing is captured on the reserved `schedule` source as - **Schedules**: each firing is captured on the reserved `schedule` source as
@@ -323,7 +325,7 @@ expressions that limit which files the rule applies to.
`fired_at`). A schedule trigger is a binding on that source using the `fired_at`). A schedule trigger is a binding on that source using the
`schedule-fired` mapping, filtered to one `schedule_id`. A firing starts at `schedule-fired` mapping, filtered to one `schedule_id`. A firing starts at
most one task per binding. most one task per binding.
- **Playbooks**: a trigger (issue kind and labels) and actions that dispatch - **Playbooks**: a trigger (issue labels) and actions that dispatch
workflows. workflows.
- **Other workflows**: `workflow.call` (a child run), `workflow.handoff` (the - **Other workflows**: `workflow.call` (a child run), `workflow.handoff` (the
same task, requeued), `workflow.approve` (once approved). same task, requeued), `workflow.approve` (once approved).
+8 -2
View File
@@ -20,9 +20,11 @@ import (
"github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/events"
) )
// workflowDefinitionSource supplies the active workflow definitions. // workflowDefinitionSource supplies the active workflow definitions and the
// routes that send an issue to one by its labels.
type workflowDefinitionSource interface { type workflowDefinitionSource interface {
WorkflowDefinitions(context.Context) (workflow.WorkflowDefinitionCollection, int64, error) WorkflowDefinitions(context.Context) (workflow.WorkflowDefinitionCollection, int64, error)
IntakeRoutes(context.Context) (workflow.IntakeRoutes, error)
} }
// workflowEnablementSource supplies which workflows each org has disabled. // workflowEnablementSource supplies which workflows each org has disabled.
@@ -367,7 +369,11 @@ func (bd *BindingDispatch) disabledRoutedWorkflow(ctx context.Context, labels, i
for _, definition := range definitions.Definitions { for _, definition := range definitions.Definitions {
available[definition.ID] = struct{}{} available[definition.ID] = struct{}{}
} }
routed, resolveErr := workflow.ResolveWorkflowID(&workflow.Task{Labels: labels}, available) routes, err := bd.definitions.IntakeRoutes(ctx)
if err != nil {
return "", false, err
}
routed, resolveErr := workflow.ResolveWorkflowID(&workflow.Task{Labels: labels}, routes, available)
if resolveErr == nil { if resolveErr == nil {
enablement, err := bd.workflowEnablement(ctx) enablement, err := bd.workflowEnablement(ctx)
if err != nil { if err != nil {
+4 -5
View File
@@ -137,11 +137,10 @@ type Daemon struct {
// PlaybookLedger is the at-most-once gate action playbooks run through. // PlaybookLedger is the at-most-once gate action playbooks run through.
PlaybookLedger storecontract.PlaybookDispatcher PlaybookLedger storecontract.PlaybookDispatcher
// WorkflowDefinitions supplies the active database definitions. A task is // WorkflowDefinitions supplies the active database definitions and the
// pinned once before dispatch; retries reuse the task's stored YAML. // label routes that pick one. A task is pinned once before dispatch;
WorkflowDefinitions interface { // retries reuse the task's stored YAML.
WorkflowDefinitions(context.Context) (workflow.WorkflowDefinitionCollection, int64, error) WorkflowDefinitions workflowDefinitionSource
}
// TaskLogs persists each task's log output and mirrors it to the dashboard. // TaskLogs persists each task's log output and mirrors it to the dashboard.
// Nil disables task logging. // Nil disables task logging.
+4
View File
@@ -38,6 +38,10 @@ func (s staticDefinitions) WorkflowDefinitions(context.Context) (workflow.Workfl
return s.collection, 1, s.err return s.collection, 1, s.err
} }
func (staticDefinitions) IntakeRoutes(context.Context) (workflow.IntakeRoutes, error) {
return workflow.ShippedIntakeRoutes(), nil
}
// enablementSource serves one enablement value, or an error. // enablementSource serves one enablement value, or an error.
type enablementSource struct { type enablementSource struct {
value workflowtask.WorkflowEnablement value workflowtask.WorkflowEnablement
+2 -3
View File
@@ -238,8 +238,8 @@ func (p *IssuePoller) pollNATS(ctx context.Context, fg forge.Forge, cfg config.C
p.log.InfoContext(ctx, "issue skipped: its routed workflow is disabled for this org", "repo", repo.FullName(), "issue", is.Number, "workflow", routed) p.log.InfoContext(ctx, "issue skipped: its routed workflow is disabled for this org", "repo", repo.FullName(), "issue", is.Number, "workflow", routed)
return false return false
} }
// Classify and encode here: the envelope, its routing kind and its // Encode here: the envelope and its subject belong to the work-intake
// subject belong to the work-intake domain, not to the transport. // domain, not to the transport.
parsed := workintake.SplitLabels(labels) parsed := workintake.SplitLabels(labels)
task := workintake.TaskEnvelope{ task := workintake.TaskEnvelope{
Owner: repo.Owner, Owner: repo.Owner,
@@ -249,7 +249,6 @@ func (p *IssuePoller) pollNATS(ctx context.Context, fg forge.Forge, cfg config.C
Body: is.Body, Body: is.Body,
Labels: parsed, Labels: parsed,
Identity: identity, Identity: identity,
Kind: workintake.KindForLabels(parsed),
} }
if err := p.publishTask(ctx, task); err != nil { if err := p.publishTask(ctx, task); err != nil {
p.log.ErrorContext(ctx, "task publish failed", "repo", repo.FullName(), "issue", is.Number, "err", err) p.log.ErrorContext(ctx, "task publish failed", "repo", repo.FullName(), "issue", is.Number, "err", err)
+9 -8
View File
@@ -93,7 +93,11 @@ func (d *Daemon) pinWorkflowFromCollection(ctx context.Context, task *workflow.T
for _, definition := range collection.Definitions { for _, definition := range collection.Definitions {
available[definition.ID] = struct{}{} available[definition.ID] = struct{}{}
} }
id, err := d.resolveWorkflowID(ctx, task, available) routes, err := d.WorkflowDefinitions.IntakeRoutes(ctx)
if err != nil {
return pinFailure{taskstate.ParkTransient, fmt.Errorf("intake routes: %w", err)}
}
id, err := d.resolveWorkflowID(ctx, task, routes, available)
if err != nil { if err != nil {
return pinFailure{taskstate.ParkNeedsDecision, err} return pinFailure{taskstate.ParkNeedsDecision, err}
} }
@@ -112,14 +116,14 @@ func (d *Daemon) pinWorkflowFromCollection(ctx context.Context, task *workflow.T
} }
// resolveWorkflowID picks the definition to pin: a matching playbook, then // resolveWorkflowID picks the definition to pin: a matching playbook, then
// the kind defaults. A task already naming a workflow keeps it. // the label routes. A task already naming a workflow keeps it.
func (d *Daemon) resolveWorkflowID(ctx context.Context, task *workflow.Task, available map[string]struct{}) (string, error) { func (d *Daemon) resolveWorkflowID(ctx context.Context, task *workflow.Task, routes workflow.IntakeRoutes, available map[string]struct{}) (string, error) {
if task.Workflow != "" { if task.Workflow != "" {
return workflow.ResolveWorkflowID(task, available) return workflow.ResolveWorkflowID(task, routes, available)
} }
decision, matched := d.Playbooks.Dispatch(ctx, playbookInput(task)) decision, matched := d.Playbooks.Dispatch(ctx, playbookInput(task))
if !matched { if !matched {
return workflow.ResolveWorkflowID(task, available) return workflow.ResolveWorkflowID(task, routes, available)
} }
if _, defined := available[decision.Workflow]; !defined { if _, defined := available[decision.Workflow]; !defined {
// Reported, not silently downgraded to the binding's choice: the // Reported, not silently downgraded to the binding's choice: the
@@ -151,13 +155,10 @@ func (d *Daemon) runActionPlaybooks(ctx context.Context, task *workflow.Task) {
// padded with values the daemon would have to invent. // padded with values the daemon would have to invent.
func playbookInput(task *workflow.Task) playbook.DispatchInput { func playbookInput(task *workflow.Task) playbook.DispatchInput {
labels := workintake.SplitLabels(task.Labels) labels := workintake.SplitLabels(task.Labels)
kind := string(workintake.KindForLabels(labels))
return playbook.DispatchInput{ return playbook.DispatchInput{
Labels: labels, Labels: labels,
Kind: kind,
TaskID: workintake.TaskEnvelope{Org: task.Org, Identity: task.Identity, Owner: task.Owner, Repo: task.Repo, Number: task.IssueNumber}.IdempotencyKey(), TaskID: workintake.TaskEnvelope{Org: task.Org, Identity: task.Identity, Owner: task.Owner, Repo: task.Repo, Number: task.IssueNumber}.IdempotencyKey(),
Event: map[string]any{ Event: map[string]any{
"kind": kind,
"labels": labels, "labels": labels,
"owner": task.Owner, "owner": task.Owner,
"repo": task.Repo, "repo": task.Repo,
-3
View File
@@ -281,9 +281,6 @@ func (b *TaskBus) emitTaskQueued(ctx context.Context, task *workflow.Task) {
// PublishTask validates a task envelope, stamps the producing identity's // PublishTask validates a task envelope, stamps the producing identity's
// org and publishes it. The idempotency key dedups rediscovered issues. // org and publishes it. The idempotency key dedups rediscovered issues.
func (b *TaskBus) PublishTask(ctx context.Context, task workintake.TaskEnvelope) error { func (b *TaskBus) PublishTask(ctx context.Context, task workintake.TaskEnvelope) error {
if err := task.Kind.Validate(); err != nil {
return fmt.Errorf("publish task %s: %w", task.Ref(), err)
}
if task.Identity == "" { if task.Identity == "" {
return fmt.Errorf("publish task %s: no identity", task.Ref()) return fmt.Errorf("publish task %s: no identity", task.Ref())
} }
+4
View File
@@ -228,6 +228,10 @@ func (neutralDefinitions) WorkflowDefinitions(context.Context) (workflow.Workflo
return workflow.ShippedDefinitions(), 0, nil return workflow.ShippedDefinitions(), 0, nil
} }
func (neutralDefinitions) IntakeRoutes(context.Context) (workflow.IntakeRoutes, error) {
return workflow.ShippedIntakeRoutes(), nil
}
// neutralEnablement disables no workflow. // neutralEnablement disables no workflow.
type neutralEnablement struct{} type neutralEnablement struct{}
+4
View File
@@ -129,6 +129,10 @@ func (d orgDefinitions) WorkflowDefinitions(ctx context.Context) (workflow.Workf
return workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "deploy", YAML: d[owner]}}}, 3, nil return workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "deploy", YAML: d[owner]}}}, 3, nil
} }
func (orgDefinitions) IntakeRoutes(context.Context) (workflow.IntakeRoutes, error) {
return workflow.ShippedIntakeRoutes(), nil
}
func TestPinWorkflowInTaskOrg(t *testing.T) { func TestPinWorkflowInTaskOrg(t *testing.T) {
const shared = "id: deploy\nsteps:\n - type: workflow.finish\n" const shared = "id: deploy\nsteps:\n - type: workflow.finish\n"
const custom = "id: deploy\nrepository: none\nsteps:\n - type: workflow.finish\n" const custom = "id: deploy\nrepository: none\nsteps:\n - type: workflow.finish\n"
+1 -1
View File
@@ -32,7 +32,7 @@ func Processes() []string { return []string{Daemon, Gateway, Messaging} }
// Applicability names the consumers of each resource, including boot-only settings. // Applicability names the consumers of each resource, including boot-only settings.
func Applicability() map[string][]string { func Applicability() map[string][]string {
kinds := map[string][]string{} kinds := map[string][]string{}
for _, kind := range []string{"task-policy", "provider-settings", "model-aliases", "repository-policies", "scheduling-policy", "tool-settings", "plugin-settings", "channel-settings", "container-runtime-policies", "credential-bindings", "identity-grants", "agent-profiles", "workflow-execution-settings", "extension-settings", "workflow-definitions", "workflow-enablement", "eda-playbooks", "forge-connections"} { for _, kind := range []string{"task-policy", "provider-settings", "model-aliases", "repository-policies", "scheduling-policy", "tool-settings", "plugin-settings", "channel-settings", "container-runtime-policies", "credential-bindings", "identity-grants", "agent-profiles", "workflow-execution-settings", "extension-settings", "workflow-definitions", "workflow-enablement", "intake-routes", "eda-playbooks", "forge-connections"} {
kinds[kind] = []string{Daemon} kinds[kind] = []string{Daemon}
} }
for _, kind := range []string{"provider-settings", "model-aliases", "tool-settings", "extension-settings", "soul", "skills", "curators"} { for _, kind := range []string{"provider-settings", "model-aliases", "tool-settings", "extension-settings", "soul", "skills", "curators"} {
+12 -40
View File
@@ -15,7 +15,6 @@ import (
"github.com/samcharles93/archie-core/internal/domain/eda/expr" "github.com/samcharles93/archie-core/internal/domain/eda/expr"
"github.com/samcharles93/archie-core/internal/domain/stableid" "github.com/samcharles93/archie-core/internal/domain/stableid"
"github.com/samcharles93/archie-core/internal/domain/workintake"
) )
// KindSchemas is the narrow kind-to-schema source the loader consults to // KindSchemas is the narrow kind-to-schema source the loader consults to
@@ -57,15 +56,9 @@ type Playbook struct {
Actions []Action Actions []Action
} }
// Trigger decides which incoming events this playbook matches. It reuses the // Trigger decides which incoming events this playbook matches.
// existing workintake label/kind vocabulary -- no second label-matching
// mechanism is invented here.
type Trigger struct { type Trigger struct {
// Kind is the routing kind (bug/feature); empty matches the // Labels is the label set a task must carry in full to match.
// default (unlabelled) flow.
Kind workintake.Kind
// Labels is the closed label set this trigger matches; an empty set
// matches any labels.
Labels []string Labels []string
} }
@@ -100,7 +93,6 @@ type rawPlaybook struct {
} }
type rawTrigger struct { type rawTrigger struct {
Kind string `yaml:"kind"`
Labels []string `yaml:"labels"` Labels []string `yaml:"labels"`
} }
@@ -229,17 +221,11 @@ func compileOne(doc Document, schemas KindSchemas) (*Playbook, error) {
pb := &Playbook{ pb := &Playbook{
ID: path, ID: path,
Version: fmt.Sprintf("%x", sha256.Sum256(doc.YAML)), Version: fmt.Sprintf("%x", sha256.Sum256(doc.YAML)),
Trigger: Trigger{ Trigger: Trigger{Labels: raw.Trigger.Labels},
Kind: workintake.Kind(strings.TrimSpace(raw.Trigger.Kind)),
Labels: raw.Trigger.Labels,
},
} }
if pb.Trigger.Kind == "" && len(raw.Trigger.Labels) == 0 { if len(raw.Trigger.Labels) == 0 {
return nil, fmt.Errorf("playbook %s: trigger must declare a kind or labels", path) return nil, fmt.Errorf("playbook %s: trigger must declare labels", path)
}
if err := pb.Trigger.Kind.Validate(); err != nil {
return nil, fmt.Errorf("playbook %s: %w", path, err)
} }
actions, err := compileActions(path, raw.Actions, schemas) actions, err := compileActions(path, raw.Actions, schemas)
@@ -513,12 +499,10 @@ func compileExpr(path, field, src string, env *expr.Env) (*expr.Program, error)
type DispatchInput struct { type DispatchInput struct {
// Labels are the incoming task's labels (comma-split already). // Labels are the incoming task's labels (comma-split already).
Labels []string Labels []string
// Kind is the routing kind the labels produced (workintake.KindForLabels).
Kind string
// TaskID is the originating task's idempotency key, used as the event id. // TaskID is the originating task's idempotency key, used as the event id.
TaskID string TaskID string
// Event is the event payload exposed as `event` in CEL expressions. For // Event is the event payload exposed as `event` in CEL expressions. For
// a workflow-kind dispatch this carries the label/kind fields cheaply // a workflow-kind dispatch this carries the label fields cheaply
// available at this point. // available at this point.
Event map[string]any Event map[string]any
} }
@@ -531,25 +515,13 @@ func (pb *Playbook) IsActionPlaybook() bool {
// Match reports whether the playbook's trigger matches the input's labels. // Match reports whether the playbook's trigger matches the input's labels.
func (pb *Playbook) Match(input DispatchInput) bool { func (pb *Playbook) Match(input DispatchInput) bool {
labels := input.Labels inputSet := make(map[string]bool, len(input.Labels))
if len(labels) == 0 { for _, l := range input.Labels {
labels = []string{} inputSet[strings.TrimSpace(l)] = true
} }
kind := workintake.Kind(input.Kind) for _, want := range pb.Trigger.Labels {
if !inputSet[strings.TrimSpace(want)] {
if pb.Trigger.Kind != "" && pb.Trigger.Kind != kind { return false
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 return true
+63 -44
View File
@@ -2,64 +2,83 @@ package workflow
import ( import (
"fmt" "fmt"
"strings"
"github.com/samcharles93/archie-core/internal/domain/workintake" "github.com/samcharles93/archie-core/internal/domain/workintake"
) )
// defaultKindWorkflows maps each intake kind to its default workflow. // IntakeRule sends an issue carrying Label to Workflow.
var defaultKindWorkflows = map[workintake.Kind]string{ type IntakeRule struct {
workintake.KindBug: "tdd", Label string `json:"label" title:"Label" doc:"Matched without regard to case."`
workintake.KindFeature: "feasibility", Workflow string `json:"workflow" title:"Workflow"`
} }
// IntakeRoutes is where an issue goes by its label, as a dashboard shows it: // IntakeRoutes is where an issue goes by its labels: the first rule, in list
// each kind's default workflow, and "default" for an issue with no // order, that matches one of them, else Default.
// recognised label, which goes to triage to be classified. type IntakeRoutes struct {
func IntakeRoutes() map[string]string { Rules []IntakeRule `json:"rules" title:"Rules"`
routes := map[string]string{string(workintake.KindDefault): "triage"} Default string `json:"default" title:"Default workflow" doc:"Runs an issue no rule matches."`
for kind, workflow := range defaultKindWorkflows {
routes[string(kind)] = workflow
}
return routes
} }
// workflowForLabels returns the registered workflow name for a task's // ShippedIntakeRoutes is the routing a fresh install starts with. An
// labels, trying each recognised kind in label order so a "bug,feature" task // unlabelled issue goes to triage to be classified.
// still reaches feasibility when no tdd workflow is registered. func ShippedIntakeRoutes() IntakeRoutes {
func workflowForLabels(reg Registry, labels string) (Workflow, bool) { return IntakeRoutes{
for _, kind := range workintake.KindsForLabels(workintake.SplitLabels(labels)) { Rules: []IntakeRule{{Label: "bug", Workflow: "tdd"}, {Label: "feature", Workflow: "feasibility"}},
name, ok := defaultKindWorkflows[kind] Default: "triage",
if !ok { }
continue }
}
if wf, ok := reg[name]; ok { // WorkflowFor returns the workflow an issue with these labels runs.
return wf, true func (r IntakeRoutes) WorkflowFor(labels []string) string {
for _, rule := range r.Rules {
for _, label := range labels {
if strings.EqualFold(workintake.LabelValue(label), strings.TrimSpace(rule.Label)) {
return rule.Workflow
}
} }
} }
return Workflow{}, false return r.Default
}
// Validate rejects an empty label or workflow name and a missing default.
func (r IntakeRoutes) Validate() error {
for i, rule := range r.Rules {
if strings.TrimSpace(rule.Label) == "" {
return fmt.Errorf("intake routes: rule %d has no label", i+1)
}
if strings.TrimSpace(rule.Workflow) == "" {
return fmt.Errorf("intake routes: rule %d has no workflow", i+1)
}
}
if strings.TrimSpace(r.Default) == "" {
return fmt.Errorf("intake routes: a default workflow is required")
}
return nil
}
// CheckDefined rejects a route naming a workflow that is not defined.
func (r IntakeRoutes) CheckDefined(available map[string]struct{}) error {
for _, rule := range r.Rules {
if _, ok := available[rule.Workflow]; !ok {
return fmt.Errorf("intake routes: label %q names workflow %q, which is not defined", rule.Label, rule.Workflow)
}
}
if _, ok := available[r.Default]; !ok {
return fmt.Errorf("intake routes: the default names workflow %q, which is not defined", r.Default)
}
return nil
} }
// ResolveWorkflowID deterministically selects a definition without compiling // ResolveWorkflowID deterministically selects a definition without compiling
// or executing it. It is used before worker dispatch to pin the exact YAML. // or executing it. It is used before worker dispatch to pin the exact YAML.
func ResolveWorkflowID(t *Task, available map[string]struct{}) (string, error) { func ResolveWorkflowID(t *Task, routes IntakeRoutes, available map[string]struct{}) (string, error) {
if t.Workflow != "" { id := t.Workflow
if _, ok := available[t.Workflow]; ok { if id == "" {
return t.Workflow, nil id = routes.WorkflowFor(workintake.SplitLabels(t.Labels))
}
return "", fmt.Errorf("workflow %q is not defined", t.Workflow)
} }
for _, kind := range workintake.KindsForLabels(workintake.SplitLabels(t.Labels)) { if _, ok := available[id]; !ok {
if id := defaultKindWorkflows[kind]; id != "" { return "", fmt.Errorf("workflow %q is not defined", id)
if _, ok := available[id]; ok {
return id, nil
}
}
} }
if _, ok := available["triage"]; ok { return id, nil
return "triage", nil
}
if _, ok := available["implement"]; ok {
return "implement", nil
}
return "", fmt.Errorf("no routable workflow definition")
} }
+52
View File
@@ -0,0 +1,52 @@
package workflow
import "testing"
// Guards the label to workflow contract: a label matches without regard to
// case, the first rule in list order wins when an issue carries several
// labels, and an issue no rule matches runs the default.
func TestResolveWorkflowIDByLabel(t *testing.T) {
t.Parallel()
routes := IntakeRoutes{
Rules: []IntakeRule{
{Label: "Security", Workflow: "audit"},
{Label: "bug", Workflow: "tdd"},
{Label: "feature", Workflow: "feasibility"},
},
Default: "triage",
}
available := map[string]struct{}{"audit": {}, "tdd": {}, "feasibility": {}, "triage": {}}
tests := []struct {
name string
labels string
want string
wantErr bool
}{
{name: "label matches without regard to case", labels: "BUG", want: "tdd"},
{name: "rule label case does not matter either", labels: "security", want: "audit"},
{name: "scoped label matches its value", labels: "kind::feature", want: "feasibility"},
{name: "first rule in list order wins over label order", labels: "feature,bug", want: "tdd"},
{name: "a rule earlier in the list beats a later one", labels: "bug,security", want: "audit"},
{name: "no match runs the default", labels: "priority::high", want: "triage"},
{name: "no labels runs the default", labels: "", want: "triage"},
{name: "a route to an undefined workflow is an error", labels: "bug", want: "", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
avail := available
if tt.wantErr {
avail = map[string]struct{}{"triage": {}}
}
got, err := ResolveWorkflowID(&Task{Labels: tt.labels}, routes, avail)
if (err != nil) != tt.wantErr {
t.Fatalf("err = %v, wantErr %v", err, tt.wantErr)
}
if got != tt.want {
t.Errorf("routed to %q, want %q", got, tt.want)
}
})
}
}
@@ -84,7 +84,7 @@ func TestRepoLessTaskRunsTriageFromAPrompt(t *testing.T) {
if promptTask.HasRepository() { if promptTask.HasRepository() {
t.Fatal("the prompt-only task must have no repository") t.Fatal("the prompt-only task must have no repository")
} }
id, err := ResolveWorkflowID(promptTask, available) id, err := ResolveWorkflowID(promptTask, ShippedIntakeRoutes(), available)
if err != nil { if err != nil {
t.Fatalf("route: %v", err) t.Fatalf("route: %v", err)
} }
+2 -7
View File
@@ -344,13 +344,8 @@ func Route(t *Task, reg Registry) Workflow {
}, },
}}} }}}
} }
if wf, ok := workflowForLabels(reg, t.Labels); ok { // No explicit workflow: classify with triage instead of defaulting
return wf // straight to the heaviest workflow.
}
// No explicit workflow, no label match: a labelled task already has a free,
// reliable signal and never reaches here. Everything else -- overwhelmingly
// chat-spawned tasks, which rarely carry labels -- gets classified by
// triage instead of defaulting straight to the heaviest workflow.
if wf, ok := reg["triage"]; ok { if wf, ok := reg["triage"]; ok {
return wf return wf
} }
+2 -7
View File
@@ -43,11 +43,6 @@ type TaskEnvelope struct {
// publishing. // publishing.
// Empty means the default org of a single-operator install. // Empty means the default org of a single-operator install.
Org org.OrgID `json:"org,omitempty"` Org org.OrgID `json:"org,omitempty"`
// Kind is the routing category, chosen by the publisher. Empty means
// KindDefault, which is also what messages queued before this field
// existed decode to.
Kind Kind `json:"kind,omitempty"`
} }
// envelopeWire avoids infinite recursion in the JSON methods below. // envelopeWire avoids infinite recursion in the JSON methods below.
@@ -113,8 +108,8 @@ func (t TaskEnvelope) org() org.OrgID {
return t.Org return t.Org
} }
// Subject returns the address this envelope routes to. // Subject returns the address this envelope is published to.
func (t TaskEnvelope) Subject() string { return SubjectForKind(t.Kind) } func (t TaskEnvelope) Subject() string { return SubjectTask }
// SplitLabels parses the comma-separated wire form, dropping empties so // SplitLabels parses the comma-separated wire form, dropping empties so
// "bug,,feature" and a trailing comma do not produce blank labels. // "bug,,feature" and a trailing comma do not produce blank labels.
+10 -87
View File
@@ -1,98 +1,21 @@
package workintake package workintake
import ( import "strings"
"errors"
"fmt"
"strings"
)
// Task subjects. Each encodes the routing kind so a multi-daemon deployment // SubjectTask is where every issue-intake task is published. Routing to a
// can filter by the work it wants. // workflow happens at pin time from the intake-routes setting, so the subject
const ( // carries nothing about the issue.
SubjectTaskBug = "archie.task.bug" const SubjectTask = "archie.task.issue"
SubjectTaskFeature = "archie.task.feature"
SubjectTaskDefault = "archie.task.default"
// SubjectTaskWildcard matches every task subject. // SubjectTaskWildcard matches every task subject.
SubjectTaskWildcard = "archie.task.>" const SubjectTaskWildcard = "archie.task.>"
)
// SubjectReactionWildcard matches every reaction subject. // SubjectReactionWildcard matches every reaction subject.
const SubjectReactionWildcard = "archie.reaction.>" const SubjectReactionWildcard = "archie.reaction.>"
// ErrUnknownKind reports a kind with no subject. Routing it to the default // LabelValue returns the part of a label after its last "::", so a scoped
// queue instead would silently misdeliver work. // label such as "kind::bug" matches the rule for "bug".
var ErrUnknownKind = errors.New("workintake: unknown task kind") func LabelValue(label string) string {
// Kind is the routing category an issue's labels select.
type Kind string
const (
KindBug Kind = "bug"
KindFeature Kind = "feature"
// KindDefault routes issues carrying no recognised label.
KindDefault Kind = "default"
)
// labelKinds maps a forge issue label to its routing kind. This is the one
// place the label vocabulary is defined.
var labelKinds = map[string]Kind{
"bug": KindBug,
"feature": KindFeature,
}
// kindSubjects is the closed set of routable kinds.
var kindSubjects = map[Kind]string{
KindBug: SubjectTaskBug,
KindFeature: SubjectTaskFeature,
KindDefault: SubjectTaskDefault,
}
// Validate reports whether the kind is routable. The zero kind is accepted
// and means KindDefault, so a caller that does not classify still publishes.
func (k Kind) Validate() error {
if k == "" {
return nil
}
if _, ok := kindSubjects[k]; !ok {
return fmt.Errorf("%w: %q", ErrUnknownKind, string(k))
}
return nil
}
// SubjectForKind renders a kind as its task subject. The zero and any
// unrecognised kind render as SubjectTaskDefault so a message is never
// addressed to an unroutable subject; publishers validate first.
func SubjectForKind(kind Kind) string {
if subject, ok := kindSubjects[kind]; ok {
return subject
}
return SubjectTaskDefault
}
// KindForLabels returns the routing kind for a set of issue labels. The first
// recognised label wins; an empty or unrecognised set is KindDefault.
func KindForLabels(labels []string) Kind {
for _, kind := range KindsForLabels(labels) {
return kind
}
return KindDefault
}
// KindsForLabels returns every recognised kind, in label order.
func KindsForLabels(labels []string) []Kind {
var kinds []Kind
for _, label := range labels {
if kind, ok := labelKinds[labelValue(label)]; ok {
kinds = append(kinds, kind)
}
}
return kinds
}
// labelValue returns the part of a label after its last "::".
func labelValue(label string) string {
trimmed := strings.TrimSpace(label) trimmed := strings.TrimSpace(label)
if i := strings.LastIndex(trimmed, "::"); i >= 0 { if i := strings.LastIndex(trimmed, "::"); i >= 0 {
return strings.TrimSpace(trimmed[i+len("::"):]) return strings.TrimSpace(trimmed[i+len("::"):])
+1 -1
View File
@@ -27,7 +27,7 @@ type IntegrationSource interface {
// soul is the instructions text, task-policy and org-model-policy carry limits // soul is the instructions text, task-policy and org-model-policy carry limits
// and settings whose secrets are references, never values. // and settings whose secrets are references, never values.
var readableKinds = []string{ var readableKinds = []string{
"workflow-execution-settings", "workflow-enablement", "agent-profiles", "skills", "workflow-execution-settings", "workflow-enablement", "intake-routes", "agent-profiles", "skills",
"eda-playbooks", "credential-bindings", "identity-grants", "eda-playbooks", "credential-bindings", "identity-grants",
"soul", "task-policy", "org-model-policy", "soul", "task-policy", "org-model-policy",
} }
@@ -169,7 +169,7 @@ func (s *Server) Command(ctx context.Context, request *pb.CommandRequest) (*pb.C
// org that has configured nothing has nothing, rather than the system org's // org that has configured nothing has nothing, rather than the system org's
// configuration or a not-found the dashboard cannot tell from a failure. // configuration or a not-found the dashboard cannot tell from a failure.
var orgSeededKinds = map[string]bool{ var orgSeededKinds = map[string]bool{
WorkflowDefinitionsKind: true, WorkflowEnablementKind: true, WorkflowDefinitionsKind: true, WorkflowEnablementKind: true, IntakeRoutesKind: true,
ForgeConnectionsKind: true, RepositoryPoliciesKind: true, ForgeConnectionsKind: true, RepositoryPoliciesKind: true,
} }
@@ -8,7 +8,7 @@ import (
// Schemas are not declared here: each Definition names its document type, and // Schemas are not declared here: each Definition names its document type, and
// Definition.Descriptor derives the JSON Schema from it (internal/infrastructure/controlplanestore/schema.go). // Definition.Descriptor derives the JSON Schema from it (internal/infrastructure/controlplanestore/schema.go).
func builtinDefinitions(steps workflow.StepRegistry, types map[string]workflow.StepType) []Definition { func builtinDefinitions(steps workflow.StepRegistry, types map[string]workflow.StepType) []Definition {
definitions := []Definition{taskPolicyDefinition(), workflowDefinition(), workflowDefinitionsDefinition(steps, types), workflowDraftsDefinition(), workflowEnablementDefinition(), curatorDefinition(), soulDefinition(), agentProfileDefinition(), playbooksDefinition(), skillsDefinition(), credentialBindingsDefinition(), identityGrantsDefinition(), orgModelPolicyDefinition(), forgeConnectionsDefinition()} definitions := []Definition{taskPolicyDefinition(), workflowDefinition(), workflowDefinitionsDefinition(steps, types), workflowDraftsDefinition(), workflowEnablementDefinition(), intakeRoutesDefinition(), curatorDefinition(), soulDefinition(), agentProfileDefinition(), playbooksDefinition(), skillsDefinition(), credentialBindingsDefinition(), identityGrantsDefinition(), orgModelPolicyDefinition(), forgeConnectionsDefinition()}
definitions = append(definitions, modelDefinitions()...) definitions = append(definitions, modelDefinitions()...)
definitions = append(definitions, operationalDefinitions()...) definitions = append(definitions, operationalDefinitions()...)
return definitions return definitions
@@ -0,0 +1,70 @@
package controlplanestore
import (
"context"
"encoding/json"
"fmt"
"github.com/samcharles93/archie-core/internal/config"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
)
// IntakeRoutesKind is the resource holding which workflow an issue runs by
// its labels.
const IntakeRoutesKind = "intake-routes"
func intakeRoutesDefinition() Definition {
return Definition{
Kind: IntakeRoutesKind,
Title: "Issue routing",
Document: workflow.IntakeRoutes{},
ApplyMode: "live",
Seed: func(config.Config) any { return workflow.ShippedIntakeRoutes() },
Validate: func(input []byte) error {
return validateAs(input, func(routes workflow.IntakeRoutes) error { return routes.Validate() })
},
}
}
// checkIntakeRoutes refuses routes naming a workflow the writing org has not
// defined.
func (s *Server) checkIntakeRoutes(ctx context.Context, orgID string, value []byte) error {
var routes workflow.IntakeRoutes
if err := json.Unmarshal(value, &routes); err != nil {
return err
}
stored, err := s.resource(ctx, orgID, WorkflowDefinitionsKind)
if err != nil {
return err
}
collection, err := workflow.DecodeDefinitionCollection(stored.Value, s.steps)
if err != nil {
return err
}
available := make(map[string]struct{}, len(collection.Definitions))
for _, definition := range collection.Definitions {
available[definition.ID] = struct{}{}
}
if err := routes.CheckDefined(available); err != nil {
return fmt.Errorf("%w: %w", ErrValidation, err)
}
return nil
}
// IntakeRoutes returns where the caller's org sends an issue by its labels.
func (c *WorkflowDefinitionsClient) IntakeRoutes(ctx context.Context) (workflow.IntakeRoutes, error) {
response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: IntakeRoutesKind})
if err != nil {
c.ApplyStatus.Report(ctx, IntakeRoutesKind, 0, err)
return workflow.IntakeRoutes{}, controlplanerpc.ClientError(err)
}
var routes workflow.IntakeRoutes
err = json.Unmarshal(response.Resource.ValueJson, &routes)
if err == nil {
err = routes.Validate()
}
c.ApplyStatus.Report(ctx, IntakeRoutesKind, response.Resource.Version, err)
return routes, err
}
@@ -216,6 +216,8 @@ func (s *Server) checkOrgWrite(ctx context.Context, orgID, kind string, value []
return s.checkAliasWrite(ctx, orgID, value) return s.checkAliasWrite(ctx, orgID, value)
case WorkflowDefinitionsKind: case WorkflowDefinitionsKind:
return s.checkModelAliases(ctx, orgID, value) return s.checkModelAliases(ctx, orgID, value)
case IntakeRoutesKind:
return s.checkIntakeRoutes(ctx, orgID, value)
} }
return nil return nil
} }
@@ -45,7 +45,7 @@ func workflowDefinitionsDefinition(steps workflow.StepRegistry, types map[string
value, err := json.Marshal(collection) value, err := json.Marshal(collection)
return value, removed, err return value, removed, err
}, },
SchemaExtensions: map[string]any{"x-step-types": stepTypeVocabulary(steps, types), "x-intake-routes": workflow.IntakeRoutes()}, SchemaExtensions: map[string]any{"x-step-types": stepTypeVocabulary(steps, types)},
} }
} }
+1 -1
View File
@@ -41,7 +41,7 @@ const orgSpecs: NavSpec[] = [
}, },
{ {
label: "Automation", label: "Automation",
paths: ["/org/schedules", "/org/scheduling-policy", "/org/channels", "/org/playbooks", "/org/alerts"], paths: ["/org/schedules", "/org/scheduling-policy", "/org/issue-routing", "/org/channels", "/org/playbooks", "/org/alerts"],
}, },
{ {
label: "Usage", label: "Usage",
+6
View File
@@ -301,6 +301,12 @@ const routes = [
component: SchedulingPolicyPage, component: SchedulingPolicyPage,
meta: { section: "org_config", label: "Scheduling policy", navPath: "/org", description: "Work discovery and forge labels." }, meta: { section: "org_config", label: "Scheduling policy", navPath: "/org", description: "Work discovery and forge labels." },
}, },
{
path: "issue-routing",
name: "org-issue-routing",
component: () => import("@/settings/IssueRoutingPage.vue"),
meta: { section: "org_config", label: "Issue routing", navPath: "/org", description: "Which workflow an issue runs by its labels." },
},
{ {
path: "alerts", path: "alerts",
name: "org-alerts", name: "org-alerts",
+119
View File
@@ -0,0 +1,119 @@
<script setup lang="ts">
import { ArrowDown, ArrowUp, Trash2 } from "@lucide/vue";
import { computed, onMounted, ref } from "vue";
import PageHeader from "@/base/PageHeader.vue";
import OptionSelect from "@/components/OptionSelect.vue";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Input } from "@/components/ui/input";
import { Section } from "@/components/ui/section";
import { SettingRow } from "@/components/ui/setting-row";
import { useSettingsStore } from "@/stores/settings";
import { useWorkflowsStore } from "@/stores/workflows";
import ApplyStatusRows from "./ApplyStatusRows.vue";
import HistoryLink from "./HistoryLink.vue";
import KindGate from "./KindGate.vue";
const KIND = "intake-routes";
interface IntakeRoutes {
rules: { label: string; workflow: string }[];
default: string;
}
const store = useSettingsStore();
const workflows = useWorkflowsStore();
onMounted(store.load);
const form = computed(() => store.formFor(KIND));
const routes = computed(() => store.draftValue(KIND) as IntakeRoutes | undefined);
const rules = computed(() => routes.value?.rules ?? []);
const error = computed(() => store.catalogError || store.pageErrorFor(KIND));
const options = computed(() => workflows.collection.definitions.map(({ id }) => ({ value: id, label: id })));
const label = ref("");
const workflow = ref("");
const canAdd = computed(() => label.value.trim() !== "" && workflow.value !== "");
function edit(next: Partial<IntakeRoutes>) {
if (routes.value) store.setDraftValue(KIND, { ...routes.value, ...next });
}
function add() {
if (!canAdd.value) return;
edit({ rules: [...rules.value, { label: label.value.trim(), workflow: workflow.value }] });
label.value = "";
}
function remove(index: number) {
edit({ rules: rules.value.filter((_, i) => i !== index) });
}
function move(index: number, by: -1 | 1) {
const next = [...rules.value];
const [rule] = next.splice(index, 1);
next.splice(index + by, 0, rule!);
edit({ rules: next });
}
</script>
<template>
<div>
<PageHeader title="Issue routing"><HistoryLink :kinds="[KIND]" /></PageHeader>
<ApplyStatusRows :kind="KIND" class="mb-4" />
<Alert v-if="error" variant="destructive" class="mb-4"><AlertDescription>{{ error }}</AlertDescription></Alert>
<KindGate v-if="!form" :kind="KIND" />
<template v-else>
<Section title="Rules">
<form class="mb-4 flex flex-wrap items-center gap-2" @submit.prevent="add">
<Input v-model="label" aria-label="Label" placeholder="Label" class="max-w-48 font-mono" />
<OptionSelect v-model="workflow" :options="options" aria-label="Workflow" placeholder="Workflow" class="w-44" />
<Button type="submit" :disabled="!canAdd">Add rule</Button>
</form>
<Empty v-if="!rules.length"><EmptyHeader><EmptyTitle>No rules</EmptyTitle></EmptyHeader></Empty>
<ol v-else class="divide-y divide-border border-y border-border">
<li v-for="(_, i) in rules" :key="i" class="flex flex-wrap items-center gap-2 py-2">
<form.Field v-slot="{ field }" :name="`rules[${i}].label`">
<Input
:model-value="field.state.value"
:aria-label="`Label of rule ${i + 1}`"
class="max-w-48 font-mono"
@blur="field.handleBlur"
@update:model-value="field.handleChange"
/>
</form.Field>
<form.Field v-slot="{ field }" :name="`rules[${i}].workflow`">
<OptionSelect
:model-value="field.state.value"
:options="options"
:aria-label="`Workflow of rule ${i + 1}`"
class="w-44"
@update:model-value="field.handleChange"
/>
</form.Field>
<div class="ml-auto flex items-center">
<Button variant="ghost" size="icon" :disabled="i === 0" :aria-label="`Move rule ${i + 1} up`" @click="move(i, -1)"><ArrowUp /></Button>
<Button variant="ghost" size="icon" :disabled="i === rules.length - 1" :aria-label="`Move rule ${i + 1} down`" @click="move(i, 1)"><ArrowDown /></Button>
<Button variant="ghost" size="icon" :aria-label="`Remove rule ${i + 1}`" @click="remove(i)"><Trash2 /></Button>
</div>
</li>
</ol>
</Section>
<Section title="Default">
<SettingRow label="Default workflow" for="routing-default" class="border-t-0 py-0">
<form.Field v-slot="{ field }" name="default">
<OptionSelect
id="routing-default"
:model-value="field.state.value"
:options="options"
aria-label="Default workflow"
class="w-44"
@update:model-value="field.handleChange"
/>
</form.Field>
</SettingRow>
</Section>
</template>
</div>
</template>
-5
View File
@@ -76,10 +76,6 @@ export const useWorkflowsStore = defineStore("workflows", () => {
const stepTypes = computed(() => const stepTypes = computed(() =>
parse<StepTypeInfo[]>(descriptor.value?.schema_json, (value) => value["x-step-types"], []), parse<StepTypeInfo[]>(descriptor.value?.schema_json, (value) => value["x-step-types"], []),
); );
/** Where issues are routed by label, served beside the step types. */
const intakeRoutes = computed(() =>
parse<Record<string, string>>(descriptor.value?.schema_json, (value) => value["x-intake-routes"], {}),
);
/** Unpublished edits by workflow id; only a test run runs a draft. */ /** Unpublished edits by workflow id; only a test run runs a draft. */
const drafts = computed( const drafts = computed(
@@ -102,7 +98,6 @@ export const useWorkflowsStore = defineStore("workflows", () => {
collection, collection,
shipped, shipped,
stepTypes, stepTypes,
intakeRoutes,
load: settings.load, load: settings.load,
save: (next: WorkflowDefinitionCollection) => settings.replace(KIND, next), save: (next: WorkflowDefinitionCollection) => settings.replace(KIND, next),
}; };
+10 -13
View File
@@ -4,7 +4,6 @@ import { parse } from "yaml";
import { api, describeError } from "@/lib/api"; import { api, describeError } from "@/lib/api";
import { errors } from "@/copy/errors"; import { errors } from "@/copy/errors";
import { useSettingsStore } from "@/stores/settings"; import { useSettingsStore } from "@/stores/settings";
import { useWorkflowsStore } from "@/stores/workflows";
import type { Binding } from "@/bindings/binding-draft"; import type { Binding } from "@/bindings/binding-draft";
/** One way a workflow gets started. */ /** One way a workflow gets started. */
@@ -17,8 +16,8 @@ export interface WorkflowTrigger {
} }
export interface TriggerSources { export interface TriggerSources {
/** Issue label kind to workflow, with "default" for an unlabelled issue. */ /** The issue routing setting. */
routes: Record<string, string>; routes: { rules: { label: string; workflow: string }[]; default: string };
bindings: Binding[]; bindings: Binding[];
playbooks: { id: string; yaml: string }[]; playbooks: { id: string; yaml: string }[];
/** The workflows that start this one, as the server works them out. */ /** The workflows that start this one, as the server works them out. */
@@ -66,14 +65,10 @@ function parseQuietly(source: string): unknown {
/** Everything that starts the workflow named id. */ /** Everything that starts the workflow named id. */
export function triggersFor(id: string, sources: TriggerSources): WorkflowTrigger[] { export function triggersFor(id: string, sources: TriggerSources): WorkflowTrigger[] {
const triggers: WorkflowTrigger[] = []; const triggers: WorkflowTrigger[] = [];
for (const [kind, workflow] of Object.entries(sources.routes)) { for (const rule of sources.routes.rules) {
if (workflow !== id) continue; if (rule.workflow === id) triggers.push({ kind: "issue", label: `Issues labelled ${rule.label}` });
triggers.push(
kind === "default"
? { kind: "issue", label: "Unlabelled issues" }
: { kind: "issue", label: `Issues labelled ${kind}` },
);
} }
if (sources.routes.default === id) triggers.push({ kind: "issue", label: "Other issues" });
for (const binding of sources.bindings) { for (const binding of sources.bindings) {
if (binding.workflow !== id) continue; if (binding.workflow !== id) continue;
if (binding.matcher?.source === SCHEDULE_SOURCE) { if (binding.matcher?.source === SCHEDULE_SOURCE) {
@@ -90,7 +85,7 @@ export function triggersFor(id: string, sources: TriggerSources): WorkflowTrigge
if (!value.actions.some((action) => isMapping(action) && action.workflow === id)) continue; if (!value.actions.some((action) => isMapping(action) && action.workflow === id)) continue;
const trigger = isMapping(value.trigger) ? value.trigger : {}; const trigger = isMapping(value.trigger) ? value.trigger : {};
const labels = Array.isArray(trigger.labels) ? trigger.labels.join(", ") : ""; const labels = Array.isArray(trigger.labels) ? trigger.labels.join(", ") : "";
triggers.push({ kind: "playbook", label: playbook.id, detail: [trigger.kind, labels].filter(Boolean).join(" · ") }); triggers.push({ kind: "playbook", label: playbook.id, detail: labels });
} }
for (const starter of sources.startedBy) { for (const starter of sources.startedBy) {
triggers.push({ kind: "workflow", label: starter.workflow, detail: STARTED_VIA[starter.via] ?? starter.via }); triggers.push({ kind: "workflow", label: starter.workflow, detail: STARTED_VIA[starter.via] ?? starter.via });
@@ -99,13 +94,14 @@ export function triggersFor(id: string, sources: TriggerSources): WorkflowTrigge
} }
// The words for the server's start kinds. // The words for the server's start kinds.
const ROUTES = "intake-routes";
const STARTED_VIA: Record<string, string> = { call: "calls it", handoff: "hands off to it", approve: "runs it once approved" }; const STARTED_VIA: Record<string, string> = { call: "calls it", handoff: "hands off to it", approve: "runs it once approved" };
/** The triggers of the workflow named id, from the routes and definitions the /** The triggers of the workflow named id, from the routes and definitions the
* control plane serves, the stored playbooks, and the event bindings. */ * control plane serves, the stored playbooks, and the event bindings. */
export function useWorkflowTriggers(id: Ref<string>, startedBy: Readonly<Ref<{ workflow: string; via: string }[]>>) { export function useWorkflowTriggers(id: Ref<string>, startedBy: Readonly<Ref<{ workflow: string; via: string }[]>>) {
const store = useSettingsStore(); const store = useSettingsStore();
const workflows = useWorkflowsStore();
const bindings = ref<TriggerSources["bindings"]>([]); const bindings = ref<TriggerSources["bindings"]>([]);
const schedules = ref<TriggerSources["schedules"]>([]); const schedules = ref<TriggerSources["schedules"]>([]);
// A failed read is an error, not an empty trigger list: "Manual runs only" // A failed read is an error, not an empty trigger list: "Manual runs only"
@@ -119,6 +115,7 @@ export function useWorkflowTriggers(id: Ref<string>, startedBy: Readonly<Ref<{ w
// Playbook triggers come from that resource; it is read here rather // Playbook triggers come from that resource; it is read here rather
// than trusting another page to have loaded it. // than trusting another page to have loaded it.
store.stateFor("eda-playbooks").resource ? null : store.loadResource("eda-playbooks").catch(() => null), store.stateFor("eda-playbooks").resource ? null : store.loadResource("eda-playbooks").catch(() => null),
store.stateFor(ROUTES).resource ? null : store.loadResource(ROUTES).catch(() => null),
]); ]);
// A failed read keeps what was shown, beside the error. // A failed read keeps what was shown, beside the error.
if (response) bindings.value = response.bindings ?? []; if (response) bindings.value = response.bindings ?? [];
@@ -128,7 +125,7 @@ export function useWorkflowTriggers(id: Ref<string>, startedBy: Readonly<Ref<{ w
onMounted(reload); onMounted(reload);
const triggers = computed(() => const triggers = computed(() =>
triggersFor(id.value, { triggersFor(id.value, {
routes: workflows.intakeRoutes, routes: (store.stateFor(ROUTES).resource?.value as TriggerSources["routes"] | undefined) ?? { rules: [], default: "" },
bindings: bindings.value, bindings: bindings.value,
playbooks: (store.stateFor("eda-playbooks").resource?.value as { playbooks?: TriggerSources["playbooks"] } | undefined)?.playbooks ?? [], playbooks: (store.stateFor("eda-playbooks").resource?.value as { playbooks?: TriggerSources["playbooks"] } | undefined)?.playbooks ?? [],
startedBy: startedBy.value, startedBy: startedBy.value,