Files
archie/internal/domain/workflow/agent_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

198 lines
7.3 KiB
Go

package workflow
import (
"context"
"encoding/json"
"fmt"
"maps"
"slices"
"strings"
"github.com/google/jsonschema-go/jsonschema"
"gopkg.in/yaml.v3"
"github.com/samcharles93/archie-core/internal/domain/agentrun"
)
// AgentRunStepName is the step type that runs one agent mission. It needs no
// repository: the agent works in whatever workspace the task has, a worktree
// or a scratch directory.
const AgentRunStepName = "agent.run"
// resultToolName is the capture tool through which an agent.run step with a
// result schema returns its structured result.
const resultToolName = "result"
// agentRunSettings are the agent.run step's settings.
type agentRunSettings struct {
// Mission is what the agent is asked to do. The workflow's inputs are
// appended to it as structured data.
Mission string `yaml:"mission" doc:"What the agent is asked to do. May reference {{ task.* }}, {{ inputs.* }} and {{ steps.<id>.* }}."`
// Model is the model alias that runs the agent; empty means the default.
Model string `yaml:"model" doc:"The model alias that runs the agent, e.g. default or fast. Empty means default."`
// ReadOnly restricts the agent to read-only tools.
ReadOnly bool `yaml:"read_only" title:"Read only" doc:"Restrict the agent to read-only tools."`
// Gate holds the agent to the repository's gate before it may finish:
// "repository", or "test-failure" where the test command must fail
// (writing a failing reproduction). Empty means ungated.
Gate string `yaml:"gate" enum:"repository,test-failure" doc:"Hold the agent to the repository gate before it may finish; test-failure requires the tests to fail."`
// ProtectTests write-blocks the repository's test files.
ProtectTests bool `yaml:"protect_tests" title:"Protect tests" doc:"Write-block the repository test files."`
// ExtraRules is appended to the agent's system prompt.
ExtraRules string `yaml:"extra_rules" title:"Extra rules" doc:"Appended to the agent system prompt."`
// Result is a JSON Schema object. When set, the agent must return a value
// matching it, which later steps read as steps.<id>.result.
Result map[string]any `yaml:"result" doc:"A JSON Schema object the agent must return; later steps read it as steps.<id>.result."`
}
// AgentRunStepType contributes the agent.run step type.
func AgentRunStepType() StepType {
return StepType{Name: AgentRunStepName, Factory: newAgentRunStage, Settings: agentRunSettings{}}
}
func newAgentRunStage(settings yaml.Node) (Stage, error) {
var s agentRunSettings
if settings.Kind == 0 {
return Stage{}, fmt.Errorf("%s: settings.mission is required", AgentRunStepName)
}
if err := decodeSettingsStrict(settings, &s); err != nil {
return Stage{}, fmt.Errorf("%s: %w", AgentRunStepName, err)
}
if err := s.check(); err != nil {
return Stage{}, fmt.Errorf("%s: %w", AgentRunStepName, err)
}
resultTool, err := agentResultTool(s.Result)
if err != nil {
return Stage{}, fmt.Errorf("%s: settings.result: %w", AgentRunStepName, err)
}
agent := AgentStage{
Name: AgentRunStepName,
Model: s.Model,
ReadOnly: s.ReadOnly,
Mission: func(*TaskContext) string { return s.Mission },
ExtraRules: s.ExtraRules,
OnResult: func(tc *TaskContext, res agentrun.Result) error {
tc.stepResult.Summary = res.Summary
if resultTool == nil {
return nil
}
calls := res.Captures[resultToolName]
if len(calls) != 1 {
return fmt.Errorf("%s returned its result %d times (want exactly once)", AgentRunStepName, len(calls))
}
return json.Unmarshal(calls[0], &tc.stepResult.Result)
},
}
applyRepositoryControls(&agent, s)
if resultTool != nil {
agent.CaptureTools = func(*TaskContext) []agentrun.CaptureTool { return []agentrun.CaptureTool{*resultTool} }
}
stage := agent.Stage()
return Stage{Name: AgentRunStepName, Run: func(ctx context.Context, tc *TaskContext) error {
if tc.Dir == "" {
dir, branch, err := tc.Trees.Prepare(ctx, tc.Task.Owner, tc.Task.Repo, tc.Repo.BaseBranch(), tc.Task.IssueNumber, tc.Task.Title, tc.Task.Body, tc.Task.Labels, PrepareFresh)
if err != nil {
return fmt.Errorf("%s: workspace: %w", AgentRunStepName, err)
}
tc.Dir, tc.Branch = dir, branch
}
return stage.Run(ctx, tc)
}}, nil
}
func (s agentRunSettings) check() error {
if strings.TrimSpace(s.Mission) == "" {
return fmt.Errorf("settings.mission is required")
}
if s.Gate != "" && s.Gate != "repository" && s.Gate != gateExpectTestFailure {
return fmt.Errorf("settings.gate is repository, test-failure or empty, not %q", s.Gate)
}
return nil
}
// applyRepositoryControls sets the agent's gate and write protection.
func applyRepositoryControls(agent *AgentStage, s agentRunSettings) {
switch s.Gate {
case "repository":
agent.Gate = func(tc *TaskContext) agentrun.Gate { return GateFromRepo(tc.Repo, tc.Cfg.Budgets) }
case gateExpectTestFailure:
agent.Gate = func(tc *TaskContext) agentrun.Gate { return tddReproGate(tc.Repo, tc.Cfg.Budgets) }
}
if s.ProtectTests {
agent.ProtectGlobs = func(tc *TaskContext) []string {
if glob := tc.Repo.ResolvedTestGlob(); glob != "" {
return []string{glob}
}
return nil
}
}
}
// agentResultTool is the capture tool for a result schema, or nil for none.
func agentResultTool(schema map[string]any) (*agentrun.CaptureTool, error) {
if schema == nil {
return nil, nil
}
if schema["type"] != "object" {
return nil, fmt.Errorf("must be a JSON Schema with type: object")
}
params, err := json.Marshal(schema)
if err != nil {
return nil, err
}
// A schema that will not resolve cannot be enforced at call time, so the
// definition is refused here rather than accepting results it never
// checked.
var resolved jsonschema.Schema
if err := json.Unmarshal(params, &resolved); err != nil {
return nil, fmt.Errorf("must be a valid JSON Schema: %w", err)
}
if _, err := resolved.Resolve(nil); err != nil {
return nil, fmt.Errorf("must be a valid JSON Schema: %w", err)
}
var required []string
if list, ok := schema["required"].([]any); ok {
for _, field := range list {
name, ok := field.(string)
if !ok {
return nil, fmt.Errorf("required lists field names")
}
required = append(required, name)
}
}
tool := &agentrun.CaptureTool{
Name: resultToolName, Description: "Return this step's result. Call exactly once, before finish.",
Parameters: params, RequiredFields: required, MaxCalls: 1,
}
properties, _ := schema["properties"].(map[string]any)
for _, name := range slices.Sorted(maps.Keys(properties)) {
property, _ := properties[name].(map[string]any)
switch property["type"] {
case "boolean":
// Presence is enforced only for required fields, like strings:
// an optional boolean the result omits is valid.
if slices.Contains(required, name) {
tool.BooleanFields = append(tool.BooleanFields, name)
}
case "string":
if slices.Contains(required, name) {
tool.NonEmptyStrings = append(tool.NonEmptyStrings, name)
}
}
}
return tool, nil
}
// missionWithInputs appends the task's workflow inputs to a mission as a JSON
// block, so the agent reads them as structured data rather than prose.
func missionWithInputs(t *Task, mission string) string {
if t == nil || len(t.Inputs) == 0 {
return mission
}
data, err := json.MarshalIndent(t.Inputs, "", " ")
if err != nil {
return mission
}
return mission + "\n\nWorkflow inputs (JSON):\n```json\n" + string(data) + "\n```"
}