feat(workflow): add the command.run step type
archie-core-ndm8 accepted the command-step trust decision, so a stored workflow definition may run operator argv. The workflow engine has exactly one call site -- agentworker, which is what the container agent serves -- so the step runs on the container path by construction. A non-zero exit parks the run; level: warn makes it advisory. Settings mirror the repository gate's command shape (name, argv, expect_failure) so a command means the same thing in both places. The settings type is local rather than agentexec.Command because that struct carries JSON wire tags only, and YAML decoding silently dropped expect_failure -- a command declared to fail would have been reported as passing. A reflection test holds the two shapes together.
This commit is contained in:
1 parent
8f8e732b3a
commit
703692ca7a
7 files changed
+406
-13
No files matched your search
@@ -0,0 +1,172 @@
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
)
|
||||
|
||||
// CommandRunStepName is the step type that runs operator-authored argv in the
|
||||
// task worktree at its position in a stored workflow definition.
|
||||
//
|
||||
// It is the stage half of the deleted .archie/stages/*.go, and it exists only
|
||||
// because the maintainer accepted the command-step trust decision
|
||||
// (archie-core-ndm8): stored control-plane settings already drive argv
|
||||
// execution -- repository-policies' gate and preflight commands, and
|
||||
// tool-settings' stdio MCP servers -- so a command step adds no trust tier that
|
||||
// is not already live. Before that decision the vocabulary PRD said explicitly
|
||||
// that no command step type would be created to stand in for those files
|
||||
// (docs/prds/workflow-step-vocabulary.md).
|
||||
//
|
||||
// It runs where the workflow engine runs, which is the task container:
|
||||
// internal/app/agentworker is the only caller of Run
|
||||
// (internal/app/agentworker/task_execution.go), and it is what cmd/archie-agent
|
||||
// serves. The daemon never executes a stage, so this step is on the container
|
||||
// path by construction rather than by a check it performs.
|
||||
const CommandRunStepName = "command.run"
|
||||
|
||||
// commandRunLevelWarn makes a failing command advisory: it is reported and the
|
||||
// workflow continues instead of parking.
|
||||
const commandRunLevelWarn = "warn"
|
||||
|
||||
// commandRunSettings are the command.run step's settings.
|
||||
type commandRunSettings struct {
|
||||
// Level is "error" (the default) or "warn". At "warn" a non-zero exit is
|
||||
// logged and the workflow continues, which is what makes the step usable
|
||||
// for a check the operator wants to see without being stopped by it.
|
||||
Level string `yaml:"level"`
|
||||
// Run is the commands to execute, in order. The first failure ends the
|
||||
// step, so a later command does not run after an earlier one failed.
|
||||
Run []commandRunCommand `yaml:"run"`
|
||||
}
|
||||
|
||||
// commandRunCommand is one command in a command.run step's settings.
|
||||
//
|
||||
// It is a settings shape of its own rather than agentexec.Command itself
|
||||
// because these settings are decoded from YAML and agentexec.Command carries
|
||||
// wire (JSON) tags only. Reusing the wire struct here would silently drop
|
||||
// expect_failure -- the one field whose loss is hardest to notice, because a
|
||||
// command declared to fail would simply be reported as passing, and the
|
||||
// definition would say one thing while the run did another.
|
||||
//
|
||||
// Every field is still handed to agentexec.Command before execution, so the two
|
||||
// cannot mean different things; TestCommandRunCarriesEveryGateCommandField
|
||||
// holds this shape to that struct's fields in both directions.
|
||||
type commandRunCommand struct {
|
||||
Name string `yaml:"name"`
|
||||
Argv []string `yaml:"argv"`
|
||||
ExpectFailure bool `yaml:"expect_failure"`
|
||||
}
|
||||
|
||||
// command converts the settings shape into the type the execution path takes,
|
||||
// so command.run and the repository gate share one command meaning.
|
||||
func (c commandRunCommand) command() agentexec.Command {
|
||||
return agentexec.Command{Name: c.Name, Argv: c.Argv, ExpectFailure: c.ExpectFailure}
|
||||
}
|
||||
|
||||
// CommandRunStepType contributes the command.run step type.
|
||||
func CommandRunStepType() StepType {
|
||||
return StepType{Name: CommandRunStepName, Factory: newCommandRunStage}
|
||||
}
|
||||
|
||||
func newCommandRunStage(settings yaml.Node) (Stage, error) {
|
||||
if settings.Kind == 0 {
|
||||
return Stage{}, fmt.Errorf("%s: settings.run is required", CommandRunStepName)
|
||||
}
|
||||
var s commandRunSettings
|
||||
if err := settings.Decode(&s); err != nil {
|
||||
return Stage{}, fmt.Errorf("%s: %w", CommandRunStepName, err)
|
||||
}
|
||||
switch s.Level {
|
||||
case "", "error", commandRunLevelWarn:
|
||||
default:
|
||||
return Stage{}, fmt.Errorf("%s: settings.level %q (want error or warn)", CommandRunStepName, s.Level)
|
||||
}
|
||||
if len(s.Run) == 0 {
|
||||
return Stage{}, fmt.Errorf("%s: settings.run needs at least one command", CommandRunStepName)
|
||||
}
|
||||
commands := make([]agentexec.Command, 0, len(s.Run))
|
||||
for i := range s.Run {
|
||||
if len(s.Run[i].Argv) == 0 {
|
||||
return Stage{}, fmt.Errorf("%s: settings.run[%d].argv is required", CommandRunStepName, i)
|
||||
}
|
||||
// A command with no name would report a failure as "[]
|
||||
// <output>", so it borrows its program name rather than being
|
||||
// refused: the name is for the operator reading the park reason,
|
||||
// not a decision the definition has to make twice.
|
||||
if strings.TrimSpace(s.Run[i].Name) == "" {
|
||||
s.Run[i].Name = s.Run[i].Argv[0]
|
||||
}
|
||||
commands = append(commands, s.Run[i].command())
|
||||
}
|
||||
|
||||
advisory := s.Level == commandRunLevelWarn
|
||||
return Stage{Name: CommandRunStepName, Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
if tc.Dir == "" {
|
||||
return fmt.Errorf("%s: no workspace; run it after the step that prepares one", CommandRunStepName)
|
||||
}
|
||||
detail, err := runCommands(ctx, commands, tc.Dir)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if advisory {
|
||||
if tc.Log != nil {
|
||||
tc.Log.Warn("command.run step failed; advisory, so the run continues", "detail", detail, "err", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Park rather than return an error: a returned error fails the
|
||||
// attempt, while a park leaves the run for an operator to retry
|
||||
// after fixing what the command found. An outcome stops the
|
||||
// engine at this step, so later steps do not run.
|
||||
tc.Outcome = Outcome{
|
||||
Status: StatusParked,
|
||||
Detail: fmt.Sprintf("%s: %s", CommandRunStepName, detail),
|
||||
}
|
||||
return nil
|
||||
}}, nil
|
||||
}
|
||||
|
||||
// runCommands executes argv commands in dir, in order, and returns the first
|
||||
// failure's clipped output.
|
||||
//
|
||||
// It mirrors the repository gate's execution exactly
|
||||
// (internal/agentexec/harness_runner.go's runHarnessGate): argv is executed
|
||||
// directly rather than through a shell -- so the definition's argv list is the
|
||||
// argument boundary, and no quoting is interpreted -- expect_failure inverts a
|
||||
// command's result, and the output is clipped so one noisy command cannot fill
|
||||
// a park reason. The two are separate implementations of one contract; a change
|
||||
// to either is a change to both.
|
||||
func runCommands(ctx context.Context, commands []agentexec.Command, dir string) (string, error) {
|
||||
for _, c := range commands {
|
||||
cmd := exec.CommandContext(ctx, c.Argv[0], c.Argv[1:]...)
|
||||
cmd.Dir = dir
|
||||
output, err := cmd.CombinedOutput()
|
||||
switch {
|
||||
case c.ExpectFailure && err == nil:
|
||||
return fmt.Sprintf("[%s] expected this command to fail, but it passed:\n%s", c.Name, clipCommandOutput(output)),
|
||||
fmt.Errorf("command %s: expected failure", c.Name)
|
||||
case !c.ExpectFailure && err != nil:
|
||||
return fmt.Sprintf("[%s] %s\n%s", c.Name, strings.Join(c.Argv, " "), clipCommandOutput(output)),
|
||||
fmt.Errorf("command %s: %w", c.Name, err)
|
||||
}
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// clipCommandOutput bounds one command's output. The limit matches the gate's
|
||||
// (agentexec's clipGate) so a failure reads the same wherever an operator
|
||||
// encounters it.
|
||||
func clipCommandOutput(out []byte) string {
|
||||
const limit = 4000
|
||||
s := strings.TrimSpace(string(out))
|
||||
if len(s) <= limit {
|
||||
return s
|
||||
}
|
||||
return s[:limit] + "\n[output clipped]"
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
)
|
||||
|
||||
func commandRegistry() StepRegistry {
|
||||
registry := BuiltinStepRegistry()
|
||||
registry[CommandRunStepName] = newCommandRunStage
|
||||
return registry
|
||||
}
|
||||
|
||||
// compileCommandStep parses and compiles a one-step definition through the real
|
||||
// registry, so every test below drives the same parse -> compile -> run path a
|
||||
// stored definition does rather than calling the factory directly.
|
||||
func compileCommandStep(t *testing.T, settings string) Stage {
|
||||
t.Helper()
|
||||
src := "id: w\nsteps:\n - type: " + CommandRunStepName + "\n"
|
||||
if settings != "" {
|
||||
src += " settings:\n" + settings
|
||||
}
|
||||
wf, err := ParseAndCompile(src, commandRegistry())
|
||||
if err != nil {
|
||||
t.Fatalf("ParseAndCompile: %v", err)
|
||||
}
|
||||
if len(wf.Stages) != 1 {
|
||||
t.Fatalf("stages = %d, want 1", len(wf.Stages))
|
||||
}
|
||||
return wf.Stages[0]
|
||||
}
|
||||
|
||||
// TestCommandRunCarriesEveryGateCommandField holds the settings shape to the
|
||||
// gate's command type in both directions. The settings are decoded from YAML
|
||||
// and the gate's type carries wire (JSON) tags only, so the two are
|
||||
// hand-mirrored: a field present in one and missing from the other would let a
|
||||
// definition say one thing while the run did another, which is how
|
||||
// expect_failure was first dropped here. It is the same reflection guard the
|
||||
// control plane uses for its projected settings types.
|
||||
func TestCommandRunCarriesEveryGateCommandField(t *testing.T) {
|
||||
settings := reflect.TypeFor[commandRunCommand]()
|
||||
gate := reflect.TypeFor[agentexec.Command]()
|
||||
|
||||
for field := range gate.Fields() {
|
||||
name := field.Name
|
||||
if _, ok := settings.FieldByName(name); !ok {
|
||||
t.Errorf("agentexec.Command.%s has no commandRunCommand counterpart, so no definition could set it", name)
|
||||
}
|
||||
}
|
||||
for field := range settings.Fields() {
|
||||
name := field.Name
|
||||
if _, ok := gate.FieldByName(name); !ok {
|
||||
t.Errorf("commandRunCommand.%s has no agentexec.Command counterpart, so the value would be dropped", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommandRunRefusesMalformedSettings keeps the refusals at the producer: a
|
||||
// definition that cannot mean anything is rejected when it is saved, not when a
|
||||
// run reaches the step with no workspace or no command to run.
|
||||
func TestCommandRunRefusesMalformedSettings(t *testing.T) {
|
||||
for _, test := range []struct{ name, settings, want string }{
|
||||
{"no settings at all", "", "settings.run is required"},
|
||||
{"empty run list", " run: []\n", "settings.run needs at least one command"},
|
||||
{"a command with no argv", " run:\n - name: check\n", "settings.run[0].argv is required"},
|
||||
{"an unknown level", " level: shout\n run:\n - argv: [\"true\"]\n", `settings.level "shout"`},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
src := "id: w\nsteps:\n - type: " + CommandRunStepName + "\n"
|
||||
if test.settings != "" {
|
||||
src += " settings:\n" + test.settings
|
||||
}
|
||||
_, err := ParseAndCompile(src, commandRegistry())
|
||||
if err == nil || !strings.Contains(err.Error(), test.want) {
|
||||
t.Fatalf("ParseAndCompile() error = %v, want one containing %q", err, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommandRunExecutesArgvInTheWorkspace is the step's whole purpose: the
|
||||
// operator's argv runs in the task worktree, so a command can inspect or change
|
||||
// the tree its position in the definition put it next to.
|
||||
func TestCommandRunExecutesArgvInTheWorkspace(t *testing.T) {
|
||||
stage := compileCommandStep(t, " run:\n - name: write\n argv: [\"sh\", \"-c\", \"printf hi > made.txt\"]\n")
|
||||
dir := t.TempDir()
|
||||
|
||||
if err := stage.Run(context.Background(), &TaskContext{Dir: dir}); err != nil {
|
||||
t.Fatalf("Run() = %v", err)
|
||||
}
|
||||
got, err := os.ReadFile(filepath.Join(dir, "made.txt"))
|
||||
if err != nil {
|
||||
t.Fatalf("the command did not run in the workspace: %v", err)
|
||||
}
|
||||
if string(got) != "hi" {
|
||||
t.Fatalf("made.txt = %q, want %q", got, "hi")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommandRunParksOnNonZeroExit is the decision's rule: a failing command
|
||||
// parks the run rather than failing the attempt, so an operator can fix what the
|
||||
// command found and retry.
|
||||
func TestCommandRunParksOnNonZeroExit(t *testing.T) {
|
||||
stage := compileCommandStep(t, " run:\n - name: verify\n argv: [\"sh\", \"-c\", \"echo broken >&2; exit 3\"]\n")
|
||||
tc := &TaskContext{Dir: t.TempDir()}
|
||||
|
||||
if err := stage.Run(context.Background(), tc); err != nil {
|
||||
t.Fatalf("Run() = %v, want nil: a failing command parks, it does not fail the attempt", err)
|
||||
}
|
||||
if tc.Outcome.Status != StatusParked {
|
||||
t.Fatalf("Outcome.Status = %q, want %q", tc.Outcome.Status, StatusParked)
|
||||
}
|
||||
if !strings.Contains(tc.Outcome.Detail, "verify") || !strings.Contains(tc.Outcome.Detail, "broken") {
|
||||
t.Fatalf("park Detail = %q, want it to name the command and carry its output", tc.Outcome.Detail)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommandRunWarnLevelDoesNotPark is the advisory carve-out: level warn
|
||||
// reports the failure and the workflow continues.
|
||||
func TestCommandRunWarnLevelDoesNotPark(t *testing.T) {
|
||||
stage := compileCommandStep(t, " level: warn\n run:\n - name: advisory-check\n argv: [\"sh\", \"-c\", \"exit 1\"]\n")
|
||||
tc := &TaskContext{Dir: t.TempDir()}
|
||||
|
||||
if err := stage.Run(context.Background(), tc); err != nil {
|
||||
t.Fatalf("Run() = %v", err)
|
||||
}
|
||||
if tc.Outcome.Status != "" {
|
||||
t.Fatalf("Outcome.Status = %q, want empty: level warn must not stop the run", tc.Outcome.Status)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommandRunExpectFailureInvertsTheResult covers both directions of the
|
||||
// gate's inversion, because only one of them is visible from the success path:
|
||||
// an expected failure that does not happen is itself the failure.
|
||||
func TestCommandRunExpectFailureInvertsTheResult(t *testing.T) {
|
||||
t.Run("an expected failure does not park", func(t *testing.T) {
|
||||
stage := compileCommandStep(t, " run:\n - name: must-fail\n argv: [\"sh\", \"-c\", \"exit 1\"]\n expect_failure: true\n")
|
||||
tc := &TaskContext{Dir: t.TempDir()}
|
||||
if err := stage.Run(context.Background(), tc); err != nil {
|
||||
t.Fatalf("Run() = %v", err)
|
||||
}
|
||||
if tc.Outcome.Status != "" {
|
||||
t.Fatalf("Outcome.Status = %q, want empty", tc.Outcome.Status)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a command that passes when it should fail parks", func(t *testing.T) {
|
||||
stage := compileCommandStep(t, " run:\n - name: must-fail\n argv: [\"true\"]\n expect_failure: true\n")
|
||||
tc := &TaskContext{Dir: t.TempDir()}
|
||||
if err := stage.Run(context.Background(), tc); err != nil {
|
||||
t.Fatalf("Run() = %v", err)
|
||||
}
|
||||
if tc.Outcome.Status != StatusParked {
|
||||
t.Fatalf("Outcome.Status = %q, want %q", tc.Outcome.Status, StatusParked)
|
||||
}
|
||||
if !strings.Contains(tc.Outcome.Detail, "expected this command to fail") {
|
||||
t.Fatalf("park Detail = %q, want it to say the command should have failed", tc.Outcome.Detail)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestCommandRunStopsAtTheFirstFailure pins that a later command does not run
|
||||
// after an earlier one failed: running the rest would report a state the
|
||||
// operator did not ask for, and could mutate the tree after the run was already
|
||||
// decided to park.
|
||||
func TestCommandRunStopsAtTheFirstFailure(t *testing.T) {
|
||||
stage := compileCommandStep(t, strings.Join([]string{
|
||||
" run:",
|
||||
" - name: first",
|
||||
" argv: [\"sh\", \"-c\", \"exit 2\"]",
|
||||
" - name: second",
|
||||
" argv: [\"sh\", \"-c\", \"printf later > should-not-exist.txt\"]",
|
||||
"",
|
||||
}, "\n"))
|
||||
dir := t.TempDir()
|
||||
tc := &TaskContext{Dir: dir}
|
||||
|
||||
if err := stage.Run(context.Background(), tc); err != nil {
|
||||
t.Fatalf("Run() = %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "should-not-exist.txt")); !os.IsNotExist(err) {
|
||||
t.Fatalf("the second command ran after the first failed (stat err = %v)", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommandRunWithoutAWorkspaceFails names the composition mistake instead of
|
||||
// running the command in whatever directory the process happens to be in.
|
||||
func TestCommandRunWithoutAWorkspaceFails(t *testing.T) {
|
||||
stage := compileCommandStep(t, " run:\n - name: write\n argv: [\"true\"]\n")
|
||||
err := stage.Run(context.Background(), &TaskContext{})
|
||||
if err == nil || !strings.Contains(err.Error(), "no workspace") {
|
||||
t.Fatalf("Run() error = %v, want one naming the missing workspace", err)
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ type outcomeSite struct {
|
||||
// rather than discovered on a live run.
|
||||
var outcomeSites = []outcomeSite{
|
||||
{"agent_run.go", "StatusCompleted", "a chat task's agent run produced its answer: nothing to open a PR for"},
|
||||
{"command_run.go", "StatusParked", "an operator-authored command failed and the step is not advisory (level: warn)"},
|
||||
{"diff_rules.go", "StatusParked", "the diff breaks one of the repo's blocking rules"},
|
||||
{"feasibility.go", "StatusClosedWontDo", "feasibility decided this work should not be done"},
|
||||
{"feasibility.go", "StatusWaitingHuman", "the PRD is delivered and the run waits for a go/no-go"},
|
||||
|
||||
@@ -245,7 +245,7 @@ func StageRepoStages() Stage {
|
||||
return fmt.Errorf("inspect legacy repository stages: %w", err)
|
||||
}
|
||||
if len(stages) > 0 {
|
||||
return fmt.Errorf("legacy .archie/stages/*.go is unsupported; migrate repository behavior to database-backed YAML workflow steps")
|
||||
return fmt.Errorf("legacy .archie/stages/*.go is unsupported; migrate repository behavior to database-backed YAML workflow steps (the %s step type runs operator argv in the task worktree)", CommandRunStepName)
|
||||
}
|
||||
return nil
|
||||
}}
|
||||
|
||||
@@ -67,6 +67,27 @@ func (eventSteps) StepTypes() []workflow.StepType {
|
||||
return []workflow.StepType{workflow.AgentRunStepType(), workflow.WorkflowCallStepType()}
|
||||
}
|
||||
|
||||
// commandSteps is the provider for the command.run step type: the single step
|
||||
// type the maintainer's command-step trust decision allows
|
||||
// (archie-core-ndm8), and the migration target that the refusal of
|
||||
// .archie/stages/*.go now names.
|
||||
//
|
||||
// It is a contributor of exactly one step type, which is the shape
|
||||
// docs/prds/workflow-step-vocabulary.md prescribes for this case -- "a new
|
||||
// contributor of exactly one step type at a named provider" -- and it is a
|
||||
// provider of its own rather than part of repoHooks because a command step is
|
||||
// not a repository hook: repoHooks carries the replacement for .archie/gate.go,
|
||||
// whose rules the *repository* authored, while this carries the replacement for
|
||||
// .archie/stages/*.go, whose commands the *operator* authors in the stored
|
||||
// definition.
|
||||
type commandSteps struct{}
|
||||
|
||||
func (commandSteps) Name() string { return "command" }
|
||||
|
||||
func (commandSteps) StepTypes() []workflow.StepType {
|
||||
return []workflow.StepType{workflow.CommandRunStepType()}
|
||||
}
|
||||
|
||||
// Providers returns the provider set the roots that resolve a workflow step
|
||||
// type register at their composition root, before the first resolution: it is
|
||||
// what NewManager registers, and what the roots' guards read to hold a
|
||||
@@ -82,7 +103,7 @@ func (eventSteps) StepTypes() []workflow.StepType {
|
||||
// provider_secrets.go). Until one exists for step types, adding a step type
|
||||
// means adding a provider here.
|
||||
func Providers() []workflow.StepTypeProvider {
|
||||
return []workflow.StepTypeProvider{shippedStages{}, repoHooks{}, eventSteps{}}
|
||||
return []workflow.StepTypeProvider{shippedStages{}, repoHooks{}, eventSteps{}, commandSteps{}}
|
||||
}
|
||||
|
||||
// NewManager builds this process's workflow step-type manager by registering
|
||||
|
||||
Reference in new issue
Block a user