feat(workflow): retries, parallel branches, review steps; every shipped workflow is YAML and the per-workflow step types are gone
This commit is contained in:
1 parent
eeccb2e995
commit
ae99b47581
12 files changed
+545
-341
No files matched your search
@@ -2,7 +2,6 @@ package workflow
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"embed"
|
||||
"encoding/hex"
|
||||
@@ -10,8 +9,6 @@ import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"path"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
@@ -44,13 +41,25 @@ func NeedsRepository(stepType string) bool { return !repoFreeStepTypes[stepType]
|
||||
type StepRecord struct {
|
||||
// ID names the step so later steps can reference its result.
|
||||
ID string `yaml:"id,omitempty" json:"id,omitempty"`
|
||||
Type string `yaml:"type" json:"type"`
|
||||
Type string `yaml:"type,omitempty" json:"type,omitempty"`
|
||||
Settings yaml.Node `yaml:"settings,omitempty" json:"-"`
|
||||
// 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" json:"when,omitempty"`
|
||||
// OnFailure is "park" (the default) or "continue".
|
||||
OnFailure string `yaml:"on_failure,omitempty" json:"on_failure,omitempty"`
|
||||
// Retry runs a failed step again before on_failure applies.
|
||||
Retry *RetryPolicy `yaml:"retry,omitempty" json:"retry,omitempty"`
|
||||
// Parallel makes this step a set of named branches that run at the same
|
||||
// time instead of a typed step. Each branch is a list of steps.
|
||||
Parallel map[string][]StepRecord `yaml:"parallel,omitempty" json:"parallel,omitempty"`
|
||||
}
|
||||
|
||||
// RetryPolicy is how often a failed step runs again, and how long it waits
|
||||
// between attempts.
|
||||
type RetryPolicy struct {
|
||||
Attempts int `yaml:"attempts" json:"attempts"`
|
||||
Backoff string `yaml:"backoff,omitempty" json:"backoff,omitempty"`
|
||||
}
|
||||
|
||||
const onFailureContinue = "continue"
|
||||
@@ -80,92 +89,13 @@ func ParseDefinition(src string, registry StepRegistry) (YAMLDefinition, error)
|
||||
mode := definition.RepositoryMode()
|
||||
earlier := map[string]bool{}
|
||||
for i, step := range definition.Steps {
|
||||
if err := checkStep(step, mode, earlier, registry); err != nil {
|
||||
if err := checkStep(step, mode, earlier, registry, false); err != nil {
|
||||
return YAMLDefinition{}, fmt.Errorf("workflow %q step %d: %w", definition.ID, i+1, err)
|
||||
}
|
||||
if step.ID != "" {
|
||||
earlier[step.ID] = true
|
||||
}
|
||||
}
|
||||
return definition, nil
|
||||
}
|
||||
|
||||
// checkStep validates one step against the vocabulary and the steps before it.
|
||||
func checkStep(step StepRecord, mode task.RepositoryMode, earlier map[string]bool, registry StepRegistry) error {
|
||||
if err := checkStepID(step.ID, earlier); err != nil {
|
||||
return err
|
||||
}
|
||||
if step.OnFailure != "" && step.OnFailure != "park" && step.OnFailure != onFailureContinue {
|
||||
return fmt.Errorf("on_failure is park or continue, not %q", step.OnFailure)
|
||||
}
|
||||
factory, ok := registry[step.Type]
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown type %q", step.Type)
|
||||
}
|
||||
if mode != task.RepositoryRequired && NeedsRepository(step.Type) {
|
||||
return fmt.Errorf("%q needs a repository, but the workflow's repository is %s", step.Type, mode)
|
||||
}
|
||||
if err := checkReferences(step.Settings, earlier); err != nil {
|
||||
return err
|
||||
}
|
||||
if step.When != "" {
|
||||
c, err := parseCondition(step.When)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := checkReference(c.path, earlier); err != nil {
|
||||
return fmt.Errorf("when: %w", err)
|
||||
}
|
||||
}
|
||||
if _, err := factory(step.Settings); err != nil {
|
||||
return fmt.Errorf("%q settings: %w", step.Type, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Compile resolves a validated YAML definition to executable stages.
|
||||
func Compile(definition YAMLDefinition, registry StepRegistry) (Workflow, error) {
|
||||
stages := make([]Stage, 0, len(definition.Steps))
|
||||
for _, step := range definition.Steps {
|
||||
factory, ok := registry[step.Type]
|
||||
if !ok {
|
||||
return Workflow{}, fmt.Errorf("unknown workflow step type %q", step.Type)
|
||||
}
|
||||
stage, err := factory(step.Settings)
|
||||
if err != nil {
|
||||
return Workflow{}, fmt.Errorf("build workflow step %q: %w", step.Type, err)
|
||||
}
|
||||
stages = append(stages, compiledStep(step, stage.Name, factory))
|
||||
}
|
||||
return Workflow{Name: definition.ID, Stages: stages, Interface: definition.WorkflowInterface}, nil
|
||||
}
|
||||
|
||||
// compiledStep builds the step's stage at run time from its settings with
|
||||
// every reference resolved, and records what it leaves for later steps.
|
||||
func compiledStep(step StepRecord, name string, factory StepFactory) Stage {
|
||||
// ParseDefinition has already refused a condition that does not parse.
|
||||
when, _ := parseCondition(step.When)
|
||||
return Stage{Name: name, ContinueOnFailure: step.OnFailure == onFailureContinue, Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
tc.stepResult = StepResult{}
|
||||
if step.When != "" && !when.holds(tc) {
|
||||
tc.Log.Info("step skipped", "when", step.When)
|
||||
return nil
|
||||
}
|
||||
stage, err := factory(renderSettings(step.Settings, tc))
|
||||
if err != nil {
|
||||
return fmt.Errorf("step %q settings: %w", step.Type, err)
|
||||
}
|
||||
err = stage.Run(ctx, tc)
|
||||
if step.ID != "" {
|
||||
if tc.stepResults == nil {
|
||||
tc.stepResults = map[string]StepResult{}
|
||||
}
|
||||
tc.stepResults[step.ID] = tc.stepResult
|
||||
}
|
||||
return err
|
||||
}}
|
||||
}
|
||||
|
||||
// ParseAndCompile validates and compiles one definition in a single operation.
|
||||
func ParseAndCompile(src string, registry StepRegistry) (Workflow, error) {
|
||||
definition, err := ParseDefinition(src, registry)
|
||||
@@ -242,72 +172,9 @@ func DecodeDefinitionCollection(value []byte, registry StepRegistry) (WorkflowDe
|
||||
return collection, nil
|
||||
}
|
||||
|
||||
func noSettingsFactory(stage Stage) StepFactory {
|
||||
return func(settings yaml.Node) (Stage, error) {
|
||||
if settings.Kind != 0 {
|
||||
var value map[string]any
|
||||
if err := settings.Decode(&value); err != nil {
|
||||
return Stage{}, err
|
||||
}
|
||||
if len(value) != 0 {
|
||||
return Stage{}, fmt.Errorf("step type accepts no settings")
|
||||
}
|
||||
}
|
||||
return stage, nil
|
||||
}
|
||||
}
|
||||
|
||||
// retiredSteps are step types no shipped workflow uses that still resolve, as
|
||||
// inert stages, so stored definitions naming them keep parsing.
|
||||
var retiredSteps = map[string]Stage{
|
||||
// The remediate workflow's in-container resume stage moved to daemon
|
||||
// preparation; see retiredResumeStep.
|
||||
"remediate.resume": retiredResumeStep(),
|
||||
}
|
||||
|
||||
// BuiltinStepRegistry exposes every shipped stage as a typed, non-interpreted step.
|
||||
func BuiltinStepRegistry() StepRegistry {
|
||||
registry := StepRegistry{}
|
||||
for id, wf := range legacyBuiltinWorkflows() {
|
||||
for _, stage := range wf.Stages {
|
||||
registry[id+"."+stage.Name] = noSettingsFactory(stage)
|
||||
}
|
||||
}
|
||||
for name, stage := range retiredSteps {
|
||||
registry[name] = noSettingsFactory(stage)
|
||||
}
|
||||
return registry
|
||||
}
|
||||
|
||||
// ShippedDefinitions returns the restorable factory definitions.
|
||||
func ShippedDefinitions() WorkflowDefinitionCollection {
|
||||
workflows := legacyBuiltinWorkflows()
|
||||
ids := make([]string, 0, len(workflows))
|
||||
for id := range workflows {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
collection := WorkflowDefinitionCollection{Definitions: shippedYAML()}
|
||||
for _, id := range ids {
|
||||
wf := workflows[id]
|
||||
var builder strings.Builder
|
||||
fmt.Fprintf(&builder, "id: %s\nsteps:\n", id)
|
||||
for _, stage := range wf.Stages {
|
||||
fmt.Fprintf(&builder, " - type: %s.%s\n", id, stage.Name)
|
||||
}
|
||||
// Only pr-review declares inputs today; every other builtin's
|
||||
// generated YAML stays byte-identical to before this field existed.
|
||||
if len(wf.Interface.Inputs) > 0 {
|
||||
builder.WriteString("inputs:\n")
|
||||
for _, name := range sortedInputNames(wf.Interface.Inputs) {
|
||||
spec := wf.Interface.Inputs[name]
|
||||
fmt.Fprintf(&builder, " %s:\n type: %s\n required: %t\n", name, spec.Type, spec.Required)
|
||||
}
|
||||
}
|
||||
collection.Definitions = append(collection.Definitions, WorkflowDefinitionEntry{ID: id, YAML: builder.String()})
|
||||
}
|
||||
slices.SortFunc(collection.Definitions, func(a, b WorkflowDefinitionEntry) int { return strings.Compare(a.ID, b.ID) })
|
||||
return collection
|
||||
return WorkflowDefinitionCollection{Definitions: shippedYAML()}
|
||||
}
|
||||
|
||||
//go:embed shipped/*.yaml
|
||||
@@ -327,22 +194,3 @@ func shippedYAML() []WorkflowDefinitionEntry {
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
// sortedInputNames returns a Workflow.Interface's declared input names in a
|
||||
// deterministic order, so the generated YAML (and its digest) never depends
|
||||
// on map iteration order.
|
||||
func sortedInputNames(inputs map[string]task.InputSpec) []string {
|
||||
names := make([]string, 0, len(inputs))
|
||||
for name := range inputs {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
return names
|
||||
}
|
||||
|
||||
func legacyBuiltinWorkflows() Registry {
|
||||
return Registry{
|
||||
"remediate": Remediate(),
|
||||
"pr-review": PRReview(),
|
||||
}
|
||||
}
|
||||
@@ -120,23 +120,6 @@ func skipPhase(tc *TaskContext, phase string) {
|
||||
// never has more than three lenses to begin with.
|
||||
const prReviewConcurrency = 8
|
||||
|
||||
// PRReview is the pull request reviewer, a fixed pipeline of stages. The
|
||||
// precision gate and operator approval are optional, each behind its own
|
||||
// config flag.
|
||||
func PRReview() Workflow {
|
||||
return Workflow{
|
||||
Name: "pr-review",
|
||||
// pr_number is required so a binding or chat task must name a pull request.
|
||||
Interface: task.WorkflowInterface{
|
||||
Inputs: map[string]task.InputSpec{
|
||||
"pr_number": {Type: "number", Required: true},
|
||||
"depth": {Type: "string"},
|
||||
},
|
||||
},
|
||||
Stages: prReviewStandaloneStages(),
|
||||
}
|
||||
}
|
||||
|
||||
// prReviewDecisionStages are the review stages without the operator gate, so
|
||||
// the implement workflow can run them before opening its PR.
|
||||
func prReviewDecisionStages() []Stage {
|
||||
|
||||
@@ -6,8 +6,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/agentrun"
|
||||
)
|
||||
|
||||
// ErrNoReviewPayload is returned when a remediate run starts on a task that
|
||||
@@ -110,13 +108,6 @@ func orUnknown(s string) string {
|
||||
// other clipped park reasons in this package.
|
||||
const remediationRoundCapBytes = 2000
|
||||
|
||||
// retiredResumeStep is an inert stage kept so stored definitions that name it
|
||||
// still parse. The daemon now positions the worktree before the container
|
||||
// starts.
|
||||
func retiredResumeStep() Stage {
|
||||
return Stage{Name: "resume", Run: func(context.Context, *TaskContext) error { return nil }}
|
||||
}
|
||||
|
||||
// StageRemediationRoundCap parks the task with a comment once
|
||||
// Task.RemediationRounds reaches the cap; otherwise it counts the round.
|
||||
func StageRemediationRoundCap() Stage {
|
||||
@@ -145,45 +136,6 @@ func postRemediationComment(ctx context.Context, tc *TaskContext, body string) {
|
||||
}
|
||||
}
|
||||
|
||||
// remediateMission builds the builder agent's mission from the task's
|
||||
// decoded review unit, stashing it on tc.reviewUnit so later stages
|
||||
// (commit-push, reply) don't re-decode the payload. StageCheckReviewPayload
|
||||
// already guarantees the payload decodes before this stage runs.
|
||||
func remediateMission(tc *TaskContext) string {
|
||||
unit, _ := DecodeReviewUnit(tc.Task.ReviewPayload)
|
||||
tc.reviewUnit = unit
|
||||
return fmt.Sprintf(
|
||||
"Address the review comments below on pull request #%d for %s with the smallest change that "+
|
||||
"satisfies them, then run the gate.\n\n%s\n\n"+
|
||||
"Do not run git -- the orchestrator commits and pushes for you. When done, call finish with "+
|
||||
"status \"passed\" and a summary written for the human who will read your reply: what changed and "+
|
||||
"why. If nothing here actually requires a code change, call finish with status \"passed\" and say "+
|
||||
"so in the summary.",
|
||||
tc.Task.PRNumber, tc.Repo.FullName(), renderReviewUnitMission(unit),
|
||||
)
|
||||
}
|
||||
|
||||
// remediateBuildStage runs the builder agent against the task's review
|
||||
// unit. StageCheckReviewPayload runs first, so a decode failure parks the
|
||||
// run before the builder ever sees an empty mission.
|
||||
func remediateBuildStage() Stage {
|
||||
return AgentStage{
|
||||
Name: "remediate-build",
|
||||
Role: "builder",
|
||||
Gate: func(tc *TaskContext) agentrun.Gate {
|
||||
return GateFromRepo(tc.Repo, tc.Cfg.Budgets)
|
||||
},
|
||||
Mission: remediateMission,
|
||||
OnResult: func(tc *TaskContext, res agentrun.Result) error {
|
||||
tc.BuildSummary = res.Summary
|
||||
if res.Status == agentrun.StatusPassed && len(res.Changes) == 0 {
|
||||
tc.BuildNoChanges = true
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}.Stage()
|
||||
}
|
||||
|
||||
// StageCheckReviewPayload fails the run before any worktree or agent work
|
||||
// starts if the task's review payload cannot be decoded -- a dispatch bug
|
||||
// upstream, not something a builder run can recover from.
|
||||
@@ -193,71 +145,3 @@ func StageCheckReviewPayload() Stage {
|
||||
return err
|
||||
}}
|
||||
}
|
||||
|
||||
// StageRemediationCommitPush commits and pushes the remediation to the PR
|
||||
// branch. No changes is a normal outcome.
|
||||
func StageRemediationCommitPush() Stage {
|
||||
return Stage{Name: "remediate-commit-push", Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
if tc.BuildNoChanges {
|
||||
return nil
|
||||
}
|
||||
changed, err := tc.Trees.CommitAll(ctx, tc.Dir, remediationCommitMessage(tc))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !changed {
|
||||
return nil
|
||||
}
|
||||
if err := tc.Trees.Push(ctx, tc.Dir, tc.Branch); err != nil {
|
||||
return err
|
||||
}
|
||||
tc.captureChanges(ctx, capturedAfterCommitPush)
|
||||
return nil
|
||||
}}
|
||||
}
|
||||
|
||||
func remediationCommitMessage(tc *TaskContext) string {
|
||||
return fmt.Sprintf("fix: address review feedback (archie)%s", commitIssueReference("Refs", tc.Task))
|
||||
}
|
||||
|
||||
// StageRemediationReply replies to the review this run addressed, then
|
||||
// returns the task to pr_open and clears the consumed review payload so a
|
||||
// later crash-and-resume cannot reprocess it. It is the workflow's only
|
||||
// terminal stage: it always sets Outcome, so it always ends the run.
|
||||
func StageRemediationReply() Stage {
|
||||
return Stage{Name: "remediate-reply", Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
summary := tc.BuildSummary
|
||||
if tc.BuildNoChanges {
|
||||
summary = "Reviewed -- no code change was required."
|
||||
}
|
||||
reply := fmt.Sprintf("%s\n\n---\n*archie remediation, round %d*", summary, tc.Task.RemediationRounds)
|
||||
|
||||
if id, ok := tc.reviewUnit.replyTarget(); ok {
|
||||
if err := tc.Forge.ReplyToReview(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.PRNumber, id, reply); err != nil {
|
||||
tc.Log.Warn("remediation reply not posted", "pr", tc.Task.PRNumber, "comment", id, "err", err)
|
||||
}
|
||||
} else {
|
||||
postRemediationComment(ctx, tc, reply)
|
||||
}
|
||||
|
||||
tc.Task.ReviewPayload = ""
|
||||
tc.Outcome = Outcome{Status: StatusPROpen, Detail: fmt.Sprintf("remediated review round %d", tc.Task.RemediationRounds)}
|
||||
return nil
|
||||
}}
|
||||
}
|
||||
|
||||
// Remediate runs one remediation round on an open archie-owned pull request in
|
||||
// response to a review, reusing the task's worktree and branch.
|
||||
func Remediate() Workflow {
|
||||
return Workflow{
|
||||
Name: "remediate",
|
||||
Stages: []Stage{
|
||||
StageCheckReviewPayload(),
|
||||
StageRemediationRoundCap(),
|
||||
StagePrepareWorktreeOnBranch(),
|
||||
remediateBuildStage(),
|
||||
StageRemediationCommitPush(),
|
||||
StageRemediationReply(),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// Review step types: reviewing a pull request, and answering a review of
|
||||
// archie's own.
|
||||
const (
|
||||
ReviewPRStepName = "review.pr"
|
||||
ReviewRoundStepName = "review.start-round"
|
||||
ReviewReplyStepName = "review.reply"
|
||||
)
|
||||
|
||||
// ReviewStepTypes contributes the review step types.
|
||||
func ReviewStepTypes() []StepType {
|
||||
return []StepType{
|
||||
{Name: ReviewPRStepName, Factory: newReviewPRStage},
|
||||
{Name: ReviewRoundStepName, Factory: newReviewRoundStage},
|
||||
{Name: ReviewReplyStepName, Factory: newReviewReplyStage},
|
||||
}
|
||||
}
|
||||
|
||||
// newReviewPRStage runs the whole review pipeline on the task's pull request:
|
||||
// intake, anatomy, lenses, review, precision gate, verification, coverage,
|
||||
// synthesis, operator approval, merge gate and output. Its phases share
|
||||
// private state, so they run as one step.
|
||||
func newReviewPRStage(yaml.Node) (Stage, error) {
|
||||
phases := prReviewStandaloneStages()
|
||||
return Stage{Name: ReviewPRStepName, Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
for _, phase := range phases {
|
||||
if err := phase.Run(ctx, tc); err != nil {
|
||||
return fmt.Errorf("%s (%s): %w", ReviewPRStepName, phase.Name, err)
|
||||
}
|
||||
if tc.Outcome.Status != "" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}}, nil
|
||||
}
|
||||
|
||||
// newReviewRoundStage opens one remediation round: it refuses a review
|
||||
// payload that does not decode, parks with a PR comment once the repository's
|
||||
// round cap is reached, and otherwise counts the round.
|
||||
func newReviewRoundStage(yaml.Node) (Stage, error) {
|
||||
check, roundCap := StageCheckReviewPayload(), StageRemediationRoundCap()
|
||||
return Stage{Name: ReviewRoundStepName, Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
if err := check.Run(ctx, tc); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := roundCap.Run(ctx, tc); err != nil {
|
||||
return err
|
||||
}
|
||||
tc.reviewUnit, _ = DecodeReviewUnit(tc.Task.ReviewPayload)
|
||||
return nil
|
||||
}}, nil
|
||||
}
|
||||
|
||||
type reviewReplySettings struct {
|
||||
Body string `yaml:"body"`
|
||||
}
|
||||
|
||||
// newReviewReplyStage answers the review this round addressed, in its own
|
||||
// thread when it has one, clears the consumed payload so a resumed run cannot
|
||||
// address it twice, and returns the task to pr_open.
|
||||
func newReviewReplyStage(settings yaml.Node) (Stage, error) {
|
||||
var s reviewReplySettings
|
||||
if err := decodeSettings(ReviewReplyStepName, settings, &s); err != nil {
|
||||
return Stage{}, err
|
||||
}
|
||||
if strings.TrimSpace(s.Body) == "" {
|
||||
return Stage{}, fmt.Errorf("%s: settings.body is required", ReviewReplyStepName)
|
||||
}
|
||||
return Stage{Name: ReviewReplyStepName, Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
reply := fmt.Sprintf("%s\n\n---\n*archie remediation, round %d*", s.Body, tc.Task.RemediationRounds)
|
||||
if id, ok := tc.reviewUnit.replyTarget(); ok {
|
||||
if err := tc.Forge.ReplyToReview(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.PRNumber, id, reply); err != nil {
|
||||
tc.Log.Warn("remediation reply not posted", "pr", tc.Task.PRNumber, "comment", id, "err", err)
|
||||
}
|
||||
} else {
|
||||
postRemediationComment(ctx, tc, reply)
|
||||
}
|
||||
tc.Task.ReviewPayload = ""
|
||||
tc.Outcome = Outcome{Status: StatusPROpen, Detail: fmt.Sprintf("remediated review round %d", tc.Task.RemediationRounds)}
|
||||
return nil
|
||||
}}, nil
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
id: pr-review
|
||||
inputs:
|
||||
pr_number:
|
||||
type: number
|
||||
required: true
|
||||
depth:
|
||||
type: string
|
||||
required: false
|
||||
steps:
|
||||
- type: review.pr
|
||||
@@ -0,0 +1,25 @@
|
||||
id: remediate
|
||||
steps:
|
||||
- type: review.start-round
|
||||
- type: repo.prepare
|
||||
settings:
|
||||
branch: task
|
||||
- id: build
|
||||
type: agent.run
|
||||
settings:
|
||||
gate: repository
|
||||
mission: |
|
||||
Address the review comments below on pull request #{{ task.pr }} for {{ task.repository }} with the smallest change that satisfies them, then run the gate.
|
||||
|
||||
{{ task.review }}
|
||||
|
||||
Do not run git: the orchestrator commits and pushes for you. When done, call finish with status "passed" and a summary written for the human who will read your reply: what changed and why. If nothing here actually requires a code change, call finish with status "passed" and say so in the summary.
|
||||
- type: repo.commit
|
||||
settings:
|
||||
message: "fix: address review feedback (archie)"
|
||||
reference: Refs
|
||||
push: true
|
||||
if_empty: skip
|
||||
- type: review.reply
|
||||
settings:
|
||||
body: "{{ steps.build.summary }}"
|
||||
@@ -0,0 +1,307 @@
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/agentrun"
|
||||
"github.com/samcharles93/archie-core/internal/domain/stableid"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
)
|
||||
|
||||
const maxRetryAttempts = 10
|
||||
|
||||
// checkStep validates one step against the vocabulary and the steps before
|
||||
// it, and adds the ids it declares to earlier.
|
||||
func checkStep(step StepRecord, mode task.RepositoryMode, earlier map[string]bool, registry StepRegistry, inBranch bool) error {
|
||||
if err := checkStepID(step.ID, earlier); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := checkStepControls(step, earlier); err != nil {
|
||||
return err
|
||||
}
|
||||
if step.Parallel != nil {
|
||||
if err := checkParallel(step, mode, earlier, registry, inBranch); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if err := checkTypedStep(step, mode, earlier, registry, inBranch); err != nil {
|
||||
return err
|
||||
}
|
||||
if step.ID != "" {
|
||||
earlier[step.ID] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkStepControls validates the settings every step carries: when,
|
||||
// on_failure and retry.
|
||||
func checkStepControls(step StepRecord, earlier map[string]bool) error {
|
||||
if step.OnFailure != "" && step.OnFailure != "park" && step.OnFailure != onFailureContinue {
|
||||
return fmt.Errorf("on_failure is park or continue, not %q", step.OnFailure)
|
||||
}
|
||||
if step.Retry != nil {
|
||||
if step.Retry.Attempts < 1 || step.Retry.Attempts > maxRetryAttempts {
|
||||
return fmt.Errorf("retry.attempts is 1 to %d, not %d", maxRetryAttempts, step.Retry.Attempts)
|
||||
}
|
||||
if _, err := retryBackoff(step.Retry); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if step.When == "" {
|
||||
return nil
|
||||
}
|
||||
c, err := parseCondition(step.When)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := checkReference(c.path, earlier); err != nil {
|
||||
return fmt.Errorf("when: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkTypedStep(step StepRecord, mode task.RepositoryMode, earlier map[string]bool, registry StepRegistry, inBranch bool) error {
|
||||
factory, ok := registry[step.Type]
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown type %q", step.Type)
|
||||
}
|
||||
if mode != task.RepositoryRequired && NeedsRepository(step.Type) {
|
||||
return fmt.Errorf("%q needs a repository, but the workflow's repository is %s", step.Type, mode)
|
||||
}
|
||||
if inBranch && !parallelSafe(step) {
|
||||
return fmt.Errorf("%q cannot run in a parallel branch: branches share the worktree, so only read-only agent.run and workflow.call steps may run there", step.Type)
|
||||
}
|
||||
if err := checkReferences(step.Settings, earlier); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := factory(step.Settings); err != nil {
|
||||
return fmt.Errorf("%q settings: %w", step.Type, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkParallel validates each branch on its own: a branch sees the steps
|
||||
// before the parallel step and its own earlier steps, never a sibling's.
|
||||
// Every branch's ids are visible after the parallel step.
|
||||
func checkParallel(step StepRecord, mode task.RepositoryMode, earlier map[string]bool, registry StepRegistry, inBranch bool) error {
|
||||
switch {
|
||||
case step.Type != "" || step.Settings.Kind != 0:
|
||||
return errors.New("a parallel step has branches, not a type or settings")
|
||||
case inBranch:
|
||||
return errors.New("parallel steps do not nest")
|
||||
case len(step.Parallel) < 2:
|
||||
return errors.New("parallel needs at least two branches")
|
||||
}
|
||||
declared := map[string]bool{}
|
||||
for _, name := range slices.Sorted(maps.Keys(step.Parallel)) {
|
||||
if !stableid.Valid(name) {
|
||||
return fmt.Errorf("branch name %q is not a stable identifier", name)
|
||||
}
|
||||
branch := step.Parallel[name]
|
||||
if len(branch) == 0 {
|
||||
return fmt.Errorf("branch %q has no steps", name)
|
||||
}
|
||||
seen := maps.Clone(earlier)
|
||||
for i, branchStep := range branch {
|
||||
if declared[branchStep.ID] {
|
||||
return fmt.Errorf("branch %q step %d: step id %q is declared twice", name, i+1, branchStep.ID)
|
||||
}
|
||||
if err := checkStep(branchStep, mode, seen, registry, true); err != nil {
|
||||
return fmt.Errorf("branch %q step %d: %w", name, i+1, err)
|
||||
}
|
||||
if branchStep.ID != "" {
|
||||
declared[branchStep.ID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
maps.Copy(earlier, declared)
|
||||
return nil
|
||||
}
|
||||
|
||||
// parallelSafe reports whether a step may run beside others in one worktree.
|
||||
func parallelSafe(step StepRecord) bool {
|
||||
switch step.Type {
|
||||
case WorkflowCallStepName:
|
||||
return true
|
||||
case AgentRunStepName:
|
||||
var s agentRunSettings
|
||||
return step.Settings.Decode(&s) == nil && s.ReadOnly
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func retryBackoff(policy *RetryPolicy) (time.Duration, error) {
|
||||
if policy == nil || policy.Backoff == "" {
|
||||
return 0, nil
|
||||
}
|
||||
backoff, err := time.ParseDuration(policy.Backoff)
|
||||
if err != nil || backoff < 0 {
|
||||
return 0, fmt.Errorf("retry.backoff %q is not a duration", policy.Backoff)
|
||||
}
|
||||
return backoff, nil
|
||||
}
|
||||
|
||||
// Compile resolves a validated YAML definition to executable stages.
|
||||
func Compile(definition YAMLDefinition, registry StepRegistry) (Workflow, error) {
|
||||
stages := make([]Stage, 0, len(definition.Steps))
|
||||
for _, step := range definition.Steps {
|
||||
stage, err := compileStep(step, registry)
|
||||
if err != nil {
|
||||
return Workflow{}, err
|
||||
}
|
||||
stages = append(stages, stage)
|
||||
}
|
||||
return Workflow{Name: definition.ID, Stages: stages, Interface: definition.WorkflowInterface}, nil
|
||||
}
|
||||
|
||||
func compileStep(step StepRecord, registry StepRegistry) (Stage, error) {
|
||||
if step.Parallel != nil {
|
||||
return compileParallel(step, registry)
|
||||
}
|
||||
factory, ok := registry[step.Type]
|
||||
if !ok {
|
||||
return Stage{}, fmt.Errorf("unknown workflow step type %q", step.Type)
|
||||
}
|
||||
if _, err := factory(step.Settings); err != nil {
|
||||
return Stage{}, fmt.Errorf("build workflow step %q: %w", step.Type, err)
|
||||
}
|
||||
// Settings are built per run, with every reference resolved.
|
||||
return wrapStep(step, step.Type, func(ctx context.Context, tc *TaskContext) error {
|
||||
stage, err := factory(renderSettings(step.Settings, tc))
|
||||
if err != nil {
|
||||
return fmt.Errorf("step %q settings: %w", step.Type, err)
|
||||
}
|
||||
return stage.Run(ctx, tc)
|
||||
}), nil
|
||||
}
|
||||
|
||||
// wrapStep applies the controls every step shares around its body: when,
|
||||
// retry, and recording its result under its id.
|
||||
func wrapStep(step StepRecord, name string, body func(context.Context, *TaskContext) error) Stage {
|
||||
if step.ID != "" {
|
||||
name = step.ID
|
||||
}
|
||||
// ParseDefinition has already refused a condition or backoff that does
|
||||
// not parse.
|
||||
when, _ := parseCondition(step.When)
|
||||
backoff, _ := retryBackoff(step.Retry)
|
||||
attempts := 1
|
||||
if step.Retry != nil {
|
||||
attempts = step.Retry.Attempts
|
||||
}
|
||||
return Stage{Name: name, ContinueOnFailure: step.OnFailure == onFailureContinue, Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
tc.stepResult = StepResult{}
|
||||
if step.When != "" && !when.holds(tc) {
|
||||
tc.Log.Info("step skipped", "step", name, "when", step.When)
|
||||
return nil
|
||||
}
|
||||
err := runAttempts(ctx, tc, name, attempts, backoff, body)
|
||||
if step.ID != "" {
|
||||
if tc.stepResults == nil {
|
||||
tc.stepResults = map[string]StepResult{}
|
||||
}
|
||||
tc.stepResults[step.ID] = tc.stepResult
|
||||
}
|
||||
return err
|
||||
}}
|
||||
}
|
||||
|
||||
func runAttempts(ctx context.Context, tc *TaskContext, name string, attempts int, backoff time.Duration, body func(context.Context, *TaskContext) error) error {
|
||||
var err error
|
||||
for attempt := 1; attempt <= attempts; attempt++ {
|
||||
if err = body(ctx, tc); err == nil || attempt == attempts {
|
||||
return err
|
||||
}
|
||||
tc.Log.Warn("step failed; retrying", "step", name, "attempt", attempt, "of", attempts, "err", err)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return err
|
||||
case <-time.After(backoff):
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// compileParallel runs each branch in its own copy of the task context, then
|
||||
// folds the branches' results, usage and first outcome back into the run.
|
||||
func compileParallel(step StepRecord, registry StepRegistry) (Stage, error) {
|
||||
names := slices.Sorted(maps.Keys(step.Parallel))
|
||||
branches := make([][]Stage, len(names))
|
||||
for i, name := range names {
|
||||
for _, branchStep := range step.Parallel[name] {
|
||||
stage, err := compileStep(branchStep, registry)
|
||||
if err != nil {
|
||||
return Stage{}, fmt.Errorf("branch %q: %w", name, err)
|
||||
}
|
||||
branches[i] = append(branches[i], stage)
|
||||
}
|
||||
}
|
||||
return wrapStep(step, "parallel", func(ctx context.Context, tc *TaskContext) error {
|
||||
clones := make([]*TaskContext, len(branches))
|
||||
errs := make([]error, len(branches))
|
||||
var wg sync.WaitGroup
|
||||
for i := range branches {
|
||||
clones[i] = tc.branch(names[i])
|
||||
wg.Go(func() { errs[i] = runBranch(ctx, clones[i], branches[i]) })
|
||||
}
|
||||
wg.Wait()
|
||||
for i, clone := range clones {
|
||||
tc.join(clone)
|
||||
if errs[i] != nil {
|
||||
errs[i] = fmt.Errorf("branch %q: %w", names[i], errs[i])
|
||||
}
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}), nil
|
||||
}
|
||||
|
||||
func runBranch(ctx context.Context, tc *TaskContext, stages []Stage) error {
|
||||
for _, stage := range stages {
|
||||
if err := stage.Run(ctx, tc); err != nil && !stage.ContinueOnFailure {
|
||||
return err
|
||||
}
|
||||
if tc.Outcome.Status != "" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// branch is a copy of the run's context for one parallel branch. The task is
|
||||
// copied too, with its usage counters zeroed, so join can add what the branch
|
||||
// spent without the branches racing on one task.
|
||||
func (tc *TaskContext) branch(name string) *TaskContext {
|
||||
clone := *tc
|
||||
taskCopy := *tc.Task
|
||||
taskCopy.TokensUsed, taskCopy.Iterations = 0, 0
|
||||
clone.Task = &taskCopy
|
||||
clone.RunUsage = agentrun.Usage{}
|
||||
clone.Outcome = Outcome{}
|
||||
clone.stepResults = maps.Clone(tc.stepResults)
|
||||
clone.Log = tc.Log.With("branch", name)
|
||||
return &clone
|
||||
}
|
||||
|
||||
// join folds a finished branch back into the run: its step results, what it
|
||||
// spent, and its outcome when the run has none yet.
|
||||
func (tc *TaskContext) join(branch *TaskContext) {
|
||||
for id, result := range branch.stepResults {
|
||||
if _, ok := tc.stepResults[id]; !ok {
|
||||
if tc.stepResults == nil {
|
||||
tc.stepResults = map[string]StepResult{}
|
||||
}
|
||||
tc.stepResults[id] = result
|
||||
}
|
||||
}
|
||||
tc.Task.TokensUsed += branch.Task.TokensUsed
|
||||
tc.Task.Iterations += branch.Task.Iterations
|
||||
accumulateUsage(&tc.RunUsage, branch.RunUsage)
|
||||
if tc.Outcome.Status == "" {
|
||||
tc.Outcome = branch.Outcome
|
||||
}
|
||||
}
|
||||
@@ -63,7 +63,7 @@ func checkReference(path string, earlier map[string]bool) error {
|
||||
return fmt.Errorf("reference {{ %s }} must start with task, inputs or steps", path)
|
||||
}
|
||||
|
||||
var taskFields = map[string]bool{"plan": true, "title": true, "body": true, "prompt": true, "repository": true, "kind": true, "issue": true, "pr": true}
|
||||
var taskFields = map[string]bool{"review": true, "plan": true, "title": true, "body": true, "prompt": true, "repository": true, "kind": true, "issue": true, "pr": true}
|
||||
|
||||
// renderSettings returns a copy of settings with every reference replaced by
|
||||
// its value in this run. A reference to an absent value renders empty: a
|
||||
@@ -90,7 +90,7 @@ func referenceScope(tc *TaskContext) map[string]any {
|
||||
maps.Copy(inputs, t.Inputs)
|
||||
return map[string]any{
|
||||
"task": map[string]any{
|
||||
"plan": approvedPlan(t), "title": t.Title, "body": t.Body, "prompt": taskPromptBlock(t),
|
||||
"review": reviewMission(t), "plan": approvedPlan(t), "title": t.Title, "body": t.Body, "prompt": taskPromptBlock(t),
|
||||
"repository": tc.Repo.FullName(), "kind": taskKind(t),
|
||||
"issue": t.IssueNumber, "pr": t.PRNumber,
|
||||
},
|
||||
@@ -166,3 +166,13 @@ func approvedPlan(t *Task) string {
|
||||
}
|
||||
return "<approved_prd>\n" + t.Plan + "\n</approved_prd>"
|
||||
}
|
||||
|
||||
// reviewMission is the review a remediation round addresses, as the builder
|
||||
// reads it.
|
||||
func reviewMission(t *Task) string {
|
||||
unit, err := DecodeReviewUnit(t.ReviewPayload)
|
||||
if err != nil || t.ReviewPayload == "" {
|
||||
return ""
|
||||
}
|
||||
return renderReviewUnitMission(unit)
|
||||
}
|
||||
@@ -73,6 +73,50 @@ steps:
|
||||
`,
|
||||
wantErr: `when: reference {{ steps.later.result.fit }}: no earlier step has id "later"`,
|
||||
},
|
||||
{
|
||||
name: "a branch cannot read a sibling branch",
|
||||
yaml: `id: w
|
||||
repository: none
|
||||
steps:
|
||||
- parallel:
|
||||
a: [{id: x, type: agent.run, settings: {mission: m, read_only: true}}]
|
||||
b: [{type: agent.run, settings: {mission: "{{ steps.x.summary }}", read_only: true}}]
|
||||
`,
|
||||
wantErr: `branch "b" step 1: reference {{ steps.x.summary }}: no earlier step has id "x"`,
|
||||
},
|
||||
{
|
||||
name: "a branch step must not write the worktree",
|
||||
yaml: `id: w
|
||||
repository: none
|
||||
steps:
|
||||
- parallel:
|
||||
a: [{type: agent.run, settings: {mission: m}}]
|
||||
b: [{type: agent.run, settings: {mission: m, read_only: true}}]
|
||||
`,
|
||||
wantErr: "cannot run in a parallel branch",
|
||||
},
|
||||
{
|
||||
name: "every branch result is visible after the parallel step",
|
||||
yaml: `id: w
|
||||
repository: none
|
||||
steps:
|
||||
- parallel:
|
||||
a: [{id: plan, type: agent.run, settings: {mission: m, read_only: true}}]
|
||||
b: [{id: other, type: agent.run, settings: {mission: m, read_only: true}}]
|
||||
- type: agent.run
|
||||
settings: {mission: "build {{ steps.plan.summary }} / {{ steps.plan.result.verdict }} / {{ steps.plan.result.missing }}"}
|
||||
`,
|
||||
rendered: "build the plan / go / ",
|
||||
},
|
||||
{
|
||||
name: "retry attempts are bounded",
|
||||
yaml: `id: w
|
||||
repository: none
|
||||
steps:
|
||||
- {type: workflow.finish, retry: {attempts: 50}}
|
||||
`,
|
||||
wantErr: "retry.attempts is 1 to 10",
|
||||
},
|
||||
{
|
||||
name: "on_failure takes park or continue",
|
||||
yaml: `id: w
|
||||
|
||||
@@ -4,26 +4,16 @@ package workflowsteps
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
)
|
||||
|
||||
// shippedStages provides every stage of the shipped workflows as a step
|
||||
// type.
|
||||
type shippedStages struct{}
|
||||
// reviewSteps provides the pull request review and remediation step types.
|
||||
type reviewSteps struct{}
|
||||
|
||||
func (shippedStages) Name() string { return "shipped" }
|
||||
func (reviewSteps) Name() string { return "review" }
|
||||
|
||||
func (shippedStages) StepTypes() []workflow.StepType {
|
||||
registry := workflow.BuiltinStepRegistry()
|
||||
stepTypes := make([]workflow.StepType, 0, len(registry))
|
||||
for _, name := range slices.Sorted(maps.Keys(registry)) {
|
||||
stepTypes = append(stepTypes, workflow.StepType{Name: name, Factory: registry[name]})
|
||||
}
|
||||
return stepTypes
|
||||
}
|
||||
func (reviewSteps) StepTypes() []workflow.StepType { return workflow.ReviewStepTypes() }
|
||||
|
||||
// repoHooks provides the gate.diff-rules step type.
|
||||
type repoHooks struct{}
|
||||
@@ -74,7 +64,7 @@ func (controlSteps) StepTypes() []workflow.StepType { return workflow.ControlSte
|
||||
|
||||
// Providers returns the step-type providers to register.
|
||||
func Providers() []workflow.StepTypeProvider {
|
||||
return []workflow.StepTypeProvider{shippedStages{}, repoHooks{}, eventSteps{}, commandSteps{}, repositorySteps{}, controlSteps{}}
|
||||
return []workflow.StepTypeProvider{reviewSteps{}, repoHooks{}, eventSteps{}, commandSteps{}, repositorySteps{}, controlSteps{}}
|
||||
}
|
||||
|
||||
// NewManager returns a new manager with Providers registered.
|
||||
|
||||
Reference in new issue
Block a user