Files
archie/internal/domain/workflow/command_run.go
T
sam 23f87c4cea Fix/workflow eda audit (#1627)
* fix(webui): accept the merge task action

The action whitelist omitted merge, so the dashboard's Merge button on a
pr_open task was refused with 400 unknown action.

Closes: archie-core-slpoz

* fix(workflow): give each parallel branch its own outputs

Branches shared the task's Outputs map, so concurrent declared-output
writes raced (or were lost when the map started nil). Each branch now
writes a copy; join merges new outputs in branch-name order and refuses
one written by two branches as a second write.

Closes: archie-core-3a7w2

* fix(postgres): dispatch captures oldest first and keep pending ones

ListUndispatchedCaptures ordered newest first and listed captures no
binding can match (failed HMAC), so sustained intake starved older work
and bad signatures held the batch. It is now oldest first and lists only
dispatchable captures. Count retention no longer evicts a capture that
is still pending for an armed binding. The daemon lists only sources
with an enabled workflow, so captures waiting on a disabled one do not
hold the oldest-first batch.

Closes: archie-core-2et4b, archie-core-o0s0z

* fix(ui): refuse renaming a workflow onto an existing id

Saving upserts by id, so editing a workflow's id to another workflow's
id removed the open one and overwrote the other. The editor now refuses
that save and says why.

Closes: archie-core-wpoz8

* fix(workflow): reject unknown step settings at save

Step factories decoded settings with yaml.Node.Decode, which drops keys
it does not know, and settings-less steps ignored settings entirely, so a
misspelt key (readOnly for read_only) saved and silently did nothing.
Every factory now decodes strictly and settings-less steps refuse
settings; ParseDefinition runs the factories, so the save refuses them.

Closes: archie-core-8b5nk

* fix(postgres): keep a stored capture when its prune fails

InsertCapture committed the capture, then returned the prune's error, so
intake answered 500 and a sender without a delivery header retried into
a duplicate capture and a duplicate dispatch. A failed prune is now
logged and the stored capture's id returned.

Closes: archie-core-3miuh

* fix(crondelivery): fail and advance a job no runner can deliver

Router.Run returned nil for a kind with no runner, so the engine reported
a successful run while the schedule never advanced and the job fired on
every tick. The run now fails with the refusal, which the engine reports,
and the schedule advances (a one-shot is removed). The router's own
refusal event is gone with it.

Closes: archie-core-s6ahh

* fix(taskactions): stop the runs of cancelled callees

CancelExecution cancelled a caller's waited-on callees in the store, but
only the caller's run was stopped, so callee containers ran to the end.
CancelExecution now returns the callees it cancelled (nested included)
in place of the step ids nobody read, and every cancelling action stops
their runs too.

Closes: archie-core-9labz

* fix(workflow): treat a zero json.Number as false in when

Task inputs and step results decode numbers as json.Number, which truthy
did not unpack, so when: inputs.count held for a count of 0.

Closes: archie-core-uv270

* fix(webui): read a workflow's runs with a workflow-filtered page

The workflows page and the canvas run picker filtered the newest 100
tasks of every workflow client-side, so on a busy instance a workflow's
older runs were invisible. GET /api/tasks takes a workflow filter, carried
through the State Store's Tasks request to the query, and both views ask
for the selected workflow's runs.

Closes: archie-core-tpiw1

* fix(ui): load the restored workflow into the editor

Restore Defaults saved the shipped definition but left the open draft in
the editor, still marked unsaved, so a later save re-applied it. The
editor now reloads the restored definition.

Closes: archie-core-85e7w
2026-10-12 03:20:00 +11:00

138 lines
5.2 KiB
Go

package workflow
import (
"context"
"errors"
"fmt"
"os/exec"
"strings"
"gopkg.in/yaml.v3"
"github.com/samcharles93/archie-core/internal/domain/agentrun"
)
// CommandRunStepName is the step type that runs operator-authored argv in the
// task worktree, inside the agent container.
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" enum:"error,warn" doc:"error stops the run on a failing command; warn reports it and continues."`
// 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" doc:"The commands to run in order; the first failure ends the step."`
}
// commandRunCommand is one command in a command.run step's settings. It is
// the YAML shape of agentrun.Command.
type commandRunCommand struct {
Name string `yaml:"name"`
Argv []string `yaml:"argv" doc:"The program and its arguments."`
ExpectFailure bool `yaml:"expect_failure" title:"Expect failure" doc:"The command must exit non-zero."`
}
// 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() agentrun.Command {
return agentrun.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, Settings: commandRunSettings{}}
}
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 := decodeSettingsStrict(settings, &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([]agentrun.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
}
// Return the failure, with the command's clipped output as its
// text: the shared step wrapper applies retry and on_failure, and
// the engine parks with this message. Setting a parked outcome
// here instead would stop the step before either control ran.
return errors.New(detail)
}}, nil
}
// runCommands executes argv commands in dir, in order, without a shell, and
// returns the first failure's clipped output. ExpectFailure inverts a
// command's result.
func runCommands(ctx context.Context, commands []agentrun.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]"
}