Files
samandCopilot 64dfad6d53 feat(runs): add typed results and model aliases (#2043)
Also fix repository-free message.send validation (#2046) and add a single-binary development smoke path (#1977).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-18 23:47:35 +11:00

198 lines
6.1 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 defines the default workflow for investigating an event,
// requesting approval for proposed actions and reporting the findings.
func InvestigateDocument() string { return investigateDocument }
// Document defines a workflow's interface and ordered steps. The engine
// stores, compares and validates workflow definitions 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 returns the journal name. Steps without an ID use their type and
// position, which stay stable because the run pins its workflow version.
func (s Step) name(index int) string {
if s.ID != "" {
return s.ID
}
return fmt.Sprintf("%s@%d", s.Type, index)
}
// Problem describes a validation issue at a field path.
type Problem struct {
Path string `json:"path"`
Message string `json:"message"`
}
func (p Problem) String() string { return p.Path + ": " + p.Message }
// InvalidError contains the problems found during workflow validation.
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 returns a plain-language summary of each step.
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 ignores line-ending differences and surrounding whitespace when
// comparing workflow documents.
func normalise(body string) string {
return string(bytes.TrimSpace([]byte(strings.ReplaceAll(body, "\r\n", "\n"))))
}