Files
archie/modules/runs/definition.go
T
sam ce70d4f3ee feat(runs): workflow documents take today's step shape, references and when (#2039)
A step is id/type/settings with when and on_failure; the five kinds become
the types agent.run (inline mission), connector.action, approval.wait,
run.notify and workflow.sleep. Documents declare inputs, repository,
instructions, identity and profile; references are {{ task|inputs|steps }}
checked at save. Any number of approval steps, each asking only about what
was held since; actions still held at the end are put to people before the
run finishes. Triggers are refused for a workflow they can't start, and the
workflows API lists, reads and saves documents beside a step-type catalog.

Copied from internal/domain/workflow: definition.go, step_refs.go,
step_flow.go's checks, control_steps.go's when parser, vocabulary.go and
task/interface.go. stableid moves to internal/platform.
2026-11-17 18:43:45 +11:00

198 lines
6.0 KiB
Go

package runs
import (
"bytes"
_ "embed" // the starter workflow documents
"errors"
"fmt"
"io"
"regexp"
"strings"
"gopkg.in/yaml.v3"
)
//go:embed workflows/investigate.yaml
var investigateDocument string
// InvestigateDocument is the workflow document that has an agent look into the
// event that started the run, put what it proposes to people, and report.
func InvestigateDocument() string { return investigateDocument }
// Document is a workflow as data: what it declares to whatever starts it, and
// the ordered steps the engine executes. It is stored, diffed and validated as
// text.
type Document struct {
Interface `yaml:",inline"`
Steps []Step `yaml:"steps"`
}
// Step selects one step type and supplies its settings, plus the controls
// every step shares.
type Step struct {
// ID names the step so later steps can reference its result.
ID string `yaml:"id,omitempty"`
Type string `yaml:"type,omitempty"`
Settings yaml.Node `yaml:"settings,omitempty"`
// When skips the step unless the condition holds: a reference that must
// be truthy, negated with !, or compared with == or != to a literal.
When string `yaml:"when,omitempty"`
// OnFailure is "park" (the default), which fails the run, or "continue".
OnFailure string `yaml:"on_failure,omitempty"`
// Retry runs a failed step again before on_failure applies.
Retry *RetryPolicy `yaml:"retry,omitempty"`
// Parallel makes this step a set of named branches that run at the same
// time instead of a typed step.
Parallel map[string][]Step `yaml:"parallel,omitempty"`
// Switch makes this step a choice: the case named by a reference's value
// runs, else the default, else nothing.
Switch *SwitchStep `yaml:"switch,omitempty"`
}
// SwitchStep runs the steps of the case whose key equals the value On
// references, else the case named default, else nothing.
type SwitchStep struct {
On string `yaml:"on"`
Cases map[string][]Step `yaml:"cases"`
}
// RetryPolicy is how often a failed step runs again, and how long it waits
// between attempts.
type RetryPolicy struct {
Attempts int `yaml:"attempts"`
Backoff string `yaml:"backoff,omitempty"`
}
const (
onFailurePark = "park"
onFailureContinue = "continue"
)
// name is what a step's work is recorded under: its id, else its type and
// position, which a pinned document keeps stable.
func (s Step) name(index int) string {
if s.ID != "" {
return s.ID
}
return fmt.Sprintf("%s@%d", s.Type, index)
}
// Problem is one thing wrong with a document, at the path of the field.
type Problem struct {
Path string `json:"path"`
Message string `json:"message"`
}
func (p Problem) String() string { return p.Path + ": " + p.Message }
// InvalidError is the problems found in a document.
type InvalidError struct {
Problems []Problem `json:"problems"`
}
func (e *InvalidError) Error() string {
parts := make([]string, len(e.Problems))
for i, p := range e.Problems {
parts[i] = p.String()
}
return "invalid workflow: " + strings.Join(parts, "; ")
}
// ParseDocument reads a document and validates it against the step types the
// engine runs. Fields it doesn't know are an error, so a misspelt option is
// never silently ignored.
func ParseDocument(body string) (Document, error) {
var doc Document
dec := yaml.NewDecoder(strings.NewReader(body))
dec.KnownFields(true)
if err := dec.Decode(&doc); err != nil {
if errors.Is(err, io.EOF) {
return Document{}, &InvalidError{Problems: []Problem{{Path: "steps", Message: "a workflow needs steps"}}}
}
return Document{}, &InvalidError{Problems: yamlProblems(err)}
}
if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return Document{}, &InvalidError{Problems: []Problem{{Path: "document", Message: "one workflow per document"}}}
}
if problems := doc.validate(); len(problems) > 0 {
return Document{}, &InvalidError{Problems: problems}
}
return doc, nil
}
var unknownField = regexp.MustCompile(`^(line \d+): field (\S+) not found`)
// yamlProblems turns the decoder's errors into one problem each, an unknown
// field at its line.
func yamlProblems(err error) []Problem {
var typed *yaml.TypeError
if !errors.As(err, &typed) {
return []Problem{{Path: "document", Message: strings.TrimPrefix(err.Error(), "yaml: ")}}
}
out := make([]Problem, 0, len(typed.Errors))
for _, e := range typed.Errors {
if m := unknownField.FindStringSubmatch(e); m != nil {
out = append(out, Problem{Path: m[1], Message: "unknown field " + m[2]})
continue
}
out = append(out, Problem{Path: "document", Message: e})
}
return out
}
// decodeSettings decodes a step's settings the way the document itself is
// read: unknown fields are errors. yaml.Node.Decode is not strict, so the node
// is re-encoded and decoded with KnownFields.
func decodeSettings(settings yaml.Node, target any) error {
if settings.Kind == 0 {
return nil
}
raw, err := yaml.Marshal(&settings)
if err != nil {
return fmt.Errorf("re-encode settings: %w", err)
}
dec := yaml.NewDecoder(bytes.NewReader(raw))
dec.KnownFields(true)
err = dec.Decode(target)
var typed *yaml.TypeError
switch {
case err == nil, errors.Is(err, io.EOF):
return nil
case !errors.As(err, &typed):
return errors.New(strings.TrimPrefix(err.Error(), "yaml: "))
}
errs := make([]error, 0, len(typed.Errors))
for _, e := range typed.Errors {
if m := unknownSetting.FindStringSubmatch(e); m != nil {
errs = append(errs, fmt.Errorf("unknown setting %s", m[1]))
continue
}
errs = append(errs, errors.New(e))
}
return errors.Join(errs...)
}
var unknownSetting = regexp.MustCompile(`field (\S+) not found`)
// Describe says in plain language what each step does.
func (d Document) Describe() []string {
out := make([]string, 0, len(d.Steps))
for _, s := range d.Steps {
t, ok := stepTypes[s.Type]
if !ok {
continue
}
line := t.describe(s.Settings)
if s.When != "" {
line += " when " + s.When
}
out = append(out, line)
}
return out
}
// normalise is the form two documents are compared in.
func normalise(body string) string {
return string(bytes.TrimSpace([]byte(strings.ReplaceAll(body, "\r\n", "\n"))))
}