Engine: check stages, harness-agnostic delivery, read-only enforcement, complete captures

- New `type=check` stage: the server runs a `commands` block (sh -c, per
  command_timeout, workspace env) and routes on pass/fail; per-command status,
  exit code, duration and bounded output are recorded and the failing output is
  the handoff. With delivery=true it is the landing gate (commit leftovers,
  merge moved main, checks in a fresh candidate worktree, fast-forward main).
  Parser/registry, lint (silent guards), format docs, CLI inspect, app graph and
  run detail rendering.
- delivery=true is accepted on every harness (and on check stages).
- permissions.shell on claude stages maps to Bash(cmd) / Bash(prefix:*) rules
  instead of a bare Bash allow; stages without edit that change the workspace
  fail the visit with the changed files listed (allow_workspace_changes=true
  opts out; artifacts, public and harness state dirs are ignored).
- File-change capture: symlinks compared by target, untouched protected files no
  longer make captures partial, untracked caches/dependency/build output left
  out, lockfiles listed without patch, huge files compared by metadata, raised
  patch/line limits. Outcome repair follow-ups are logged and counted on the
  step (control.outcome_repairs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 12:52:16 +00:00
parent c4de1de27b
commit 87016ef5dc
47 changed files with 2674 additions and 129 deletions
+413
View File
@@ -0,0 +1,413 @@
package stage
import (
"bytes"
"context"
"errors"
"fmt"
"os/exec"
"strconv"
"strings"
"syscall"
"time"
"unicode/utf8"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
// CheckType is a stage the server runs itself: a list of shell commands in the
// run's workspace, no model. Its outcome is pass or fail, so a red tree can be
// routed back to the implementer (with the failing output as the handoff)
// before a reviewer or a landing stage ever sees it.
const CheckType = "check"
// Check outcomes. error stays the infrastructure-failure route, as for every
// stage type.
const (
CheckPass = "pass"
CheckFail = "fail"
)
// Per-command check statuses recorded on the step output.
const (
CheckStatusPassed = "passed"
CheckStatusFailed = "failed"
CheckStatusTimedOut = "timed_out"
CheckStatusNotRun = "not_run"
)
const (
maxCheckCommands = 20
maxCheckCommandBytes = 4096
defaultCommandTimeout = 30 * time.Minute
maxCheckOutputBytes = 64 << 10 // retained per failed command (head and tail)
maxPassedOutputBytes = 2 << 10 // retained per passing command (tail)
checkHandoffTailBytes = 1500 // per failed command in the handoff
checkOutputHeadBytes = 16 << 10
checkProcessWaitDelay = 5 * time.Second
checkFailureHandoffMax = 3
)
// CheckSpec is a validated check stage.
type CheckSpec struct {
Commands []string
CommandTimeout time.Duration
Timeout time.Duration
KeepGoing bool
Delivery bool
}
// CheckCommandResult is one command's recorded result (step output "checks").
type CheckCommandResult struct {
Command string `json:"command"`
Status string `json:"status"`
ExitCode int `json:"exit_code"`
DurationMS int64 `json:"duration_ms"`
Output string `json:"output,omitempty"`
Truncated bool `json:"truncated,omitempty"`
}
// CheckReport is the result of running a check stage's commands once.
type CheckReport struct {
Commands []CheckCommandResult
}
// Failed reports whether any command did not pass.
func (r CheckReport) Failed() bool {
for _, c := range r.Commands {
if c.Status != CheckStatusPassed {
return true
}
}
return false
}
type CheckStage struct{}
var _ Stage = CheckStage{}
func (CheckStage) Validate(def Definition) error {
_, err := CheckStageSpec(def)
return err
}
// CheckStageSpec validates a check stage definition and returns its settings.
func CheckStageSpec(def Definition) (CheckSpec, error) {
if EffectiveType(def.Type) != CheckType {
return CheckSpec{}, fmt.Errorf("expected check stage")
}
for name := range def.Blocks {
switch name {
case "configs", "edges", "output", "commands":
case "skills":
return CheckSpec{}, errSkillsModelOnly("check")
case "prompt", "tools", "permissions", "checks":
return CheckSpec{}, fmt.Errorf("check stages run their commands block on the server, without a model; remove the %s block", name)
default:
return CheckSpec{}, fmt.Errorf("unexpected block %q for check stage", name)
}
}
commands, err := CheckCommands(def.Blocks["commands"])
if err != nil {
return CheckSpec{}, err
}
spec := CheckSpec{Commands: commands, CommandTimeout: defaultCommandTimeout}
for key, value := range def.Configs {
switch key {
case "timeout":
case "command_timeout":
duration, err := time.ParseDuration(value)
if err != nil || duration <= 0 {
return CheckSpec{}, fmt.Errorf("command_timeout must be a positive duration, such as 10m")
}
spec.CommandTimeout = duration
case "keep_going":
if value != "true" && value != "false" {
return CheckSpec{}, fmt.Errorf("keep_going must be true or false")
}
spec.KeepGoing = value == "true"
case "delivery":
if value != "true" {
return CheckSpec{}, fmt.Errorf("delivery must be true when set")
}
spec.Delivery = true
default:
return CheckSpec{}, fmt.Errorf("unknown check config %q (use timeout, command_timeout, keep_going or delivery)", key)
}
}
if spec.Timeout, err = StageTimeout(def); err != nil {
return CheckSpec{}, err
}
for _, outcome := range []string{CheckPass, CheckFail} {
if def.Edges[outcome] == "" {
return CheckSpec{}, fmt.Errorf("check stage requires %s and %s edges", CheckPass, CheckFail)
}
}
for outcome := range def.Edges {
if outcome != CheckPass && outcome != CheckFail && outcome != "error" {
return CheckSpec{}, fmt.Errorf("check stage outcomes are %s, %s and error; remove the %s edge", CheckPass, CheckFail, outcome)
}
}
return spec, nil
}
// CheckCommands parses a commands block: one shell command per line; blank
// lines and lines starting with # are ignored.
func CheckCommands(text string) ([]string, error) {
var commands []string
for _, line := range strings.Split(text, "\n") {
command := strings.TrimSpace(line)
if command == "" || strings.HasPrefix(command, "#") {
continue
}
if len(command) > maxCheckCommandBytes {
return nil, fmt.Errorf("check command exceeds %d bytes", maxCheckCommandBytes)
}
if !utf8.ValidString(command) || strings.ContainsRune(command, 0) {
return nil, fmt.Errorf("check commands must be UTF-8 text")
}
commands = append(commands, command)
}
if len(commands) == 0 || len(commands) > maxCheckCommands {
return nil, fmt.Errorf("check stage requires a commands block with 1 to %d commands, one per line", maxCheckCommands)
}
return commands, nil
}
// Run executes the commands in place in def.Workspace. The runner calls
// RunCheckCommands directly for a delivery check (in a fresh candidate
// worktree); this is the in-place path.
func (CheckStage) Run(ctx context.Context, def Definition, _ Values) (Result, error) {
spec, err := CheckStageSpec(def)
if err != nil {
return Result{}, err
}
if strings.TrimSpace(def.Workspace) == "" {
return Result{}, fmt.Errorf("check stage has no workspace")
}
ctx, cancel := context.WithTimeout(ctx, spec.Timeout)
defer cancel()
report := RunCheckCommands(ctx, def.Workspace, spec)
if err := ctx.Err(); err != nil && !report.Failed() {
return Result{}, err
}
return CheckResult(def.Key, spec, report), nil
}
// RunCheckCommands runs every command with `sh -c` from directory, in order,
// with the directory's workspace environment. It stops at the first failure
// unless KeepGoing; later commands are recorded as not_run.
func RunCheckCommands(ctx context.Context, directory string, spec CheckSpec) CheckReport {
report := CheckReport{}
stop := false
for _, command := range spec.Commands {
if stop || ctx.Err() != nil {
report.Commands = append(report.Commands, CheckCommandResult{Command: command, Status: CheckStatusNotRun, ExitCode: -1})
continue
}
result := runCheckCommand(ctx, directory, command, spec.CommandTimeout)
report.Commands = append(report.Commands, result)
if result.Status != CheckStatusPassed && !spec.KeepGoing {
stop = true
}
}
return report
}
func runCheckCommand(ctx context.Context, directory, command string, timeout time.Duration) CheckCommandResult {
commandCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
cmd := exec.CommandContext(commandCtx, "sh", "-c", command)
cmd.Dir = directory
cmd.Env = workenv.CommandEnv(ctx, directory)
// A test suite starts children; a timeout kills the whole process group,
// and WaitDelay bounds a child that keeps the output pipes open.
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
if cmd.Process != nil {
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
}
return nil
}
cmd.WaitDelay = checkProcessWaitDelay
output := &headTailBuffer{head: checkOutputHeadBytes, limit: maxCheckOutputBytes}
cmd.Stdout = output
cmd.Stderr = output
started := time.Now()
err := cmd.Run()
result := CheckCommandResult{Command: command, DurationMS: time.Since(started).Milliseconds()}
result.Output, result.Truncated = output.String()
var exit *exec.ExitError
switch {
case err == nil:
result.Status = CheckStatusPassed
case commandCtx.Err() != nil:
result.Status = CheckStatusTimedOut
result.ExitCode = -1
if ctx.Err() != nil {
result.Output = strings.TrimRight(result.Output+"\n[stopped: the stage timeout or cancellation ended the command]", "\n")
} else {
result.Output = strings.TrimRight(result.Output+"\n[stopped: command_timeout "+timeout.String()+" reached]", "\n")
}
case errors.As(err, &exit):
result.Status = CheckStatusFailed
result.ExitCode = exit.ExitCode()
default:
result.Status = CheckStatusFailed
result.ExitCode = -1
result.Output = strings.TrimSpace(result.Output + "\n" + err.Error())
}
if result.Status == CheckStatusPassed && len(result.Output) > maxPassedOutputBytes {
cut := len(result.Output) - maxPassedOutputBytes
for cut < len(result.Output) && !utf8.RuneStart(result.Output[cut]) {
cut++
}
result.Output = "[... earlier output omitted ...]\n" + result.Output[cut:]
result.Truncated = true
}
return result
}
// CheckResult renders a report as the stage result: outcome pass or fail, the
// output.md-style markdown later stages read (handoff first, then every
// command's output), a one-line summary and the structured per-command list.
func CheckResult(key string, spec CheckSpec, report CheckReport) Result {
outcome := CheckPass
if report.Failed() {
outcome = CheckFail
}
summary := CheckSummary(report)
var b strings.Builder
b.WriteString("# outcome\n\n" + outcome + "\n\n# handoff\n\n" + summary + "\n")
failures := 0
for _, c := range report.Commands {
if c.Status != CheckStatusFailed && c.Status != CheckStatusTimedOut {
continue
}
failures++
if failures > checkFailureHandoffMax {
b.WriteString("\nMore failures are listed below.\n")
break
}
fmt.Fprintf(&b, "\n`%s` %s:\n\n~~~\n%s\n~~~\n", c.Command, checkStatusPhrase(c), tailText(c.Output, checkHandoffTailBytes))
}
if outcome == CheckFail {
b.WriteString("\nFix the cause; the server reruns these checks.\n")
}
b.WriteString("\n## Commands\n")
for _, c := range report.Commands {
fmt.Fprintf(&b, "\n### `%s`: %s\n", c.Command, checkStatusPhrase(c))
if c.Status == CheckStatusNotRun {
continue
}
if strings.TrimSpace(c.Output) == "" {
b.WriteString("\n(no output)\n")
continue
}
fmt.Fprintf(&b, "\n~~~\n%s\n~~~\n", c.Output)
}
checks := make([]any, 0, len(report.Commands))
for _, c := range report.Commands {
checks = append(checks, map[string]any{
"command": c.Command, "status": c.Status, "exit_code": c.ExitCode,
"duration_ms": c.DurationMS, "output": c.Output, "truncated": c.Truncated,
})
}
output := Values{"markdown": b.String(), "summary": summary, "checks": checks}
if spec.Delivery {
output["delivery"] = true
}
return Result{Outcome: outcome, Output: output}
}
// CheckSummary is the one-line verdict for a report.
func CheckSummary(report CheckReport) string {
total := len(report.Commands)
var failed []string
for _, c := range report.Commands {
if c.Status == CheckStatusFailed || c.Status == CheckStatusTimedOut {
failed = append(failed, c.Command)
}
}
if len(failed) == 0 {
if total == 1 {
return "1 check passed."
}
return strconv.Itoa(total) + " checks passed."
}
line := fmt.Sprintf("%d of %d checks failed: %s", len(failed), total, strings.Join(failed, "; "))
if len(line) > 180 {
line = strings.ToValidUTF8(line[:180], "") + "…"
}
return line
}
func checkStatusPhrase(c CheckCommandResult) string {
duration := (time.Duration(c.DurationMS) * time.Millisecond).Round(100 * time.Millisecond)
switch c.Status {
case CheckStatusPassed:
return "passed (" + duration.String() + ")"
case CheckStatusTimedOut:
return "timed out (" + duration.String() + ")"
case CheckStatusNotRun:
return "not run (an earlier check failed)"
default:
return fmt.Sprintf("failed with exit code %d (%s)", c.ExitCode, duration)
}
}
func tailText(text string, limit int) string {
text = strings.TrimSpace(text)
if len(text) <= limit {
if text == "" {
return "(no output)"
}
return text
}
cut := len(text) - limit
for cut < len(text) && !utf8.RuneStart(text[cut]) {
cut++
}
return "[...]\n" + text[cut:]
}
// headTailBuffer keeps the first head bytes and the last limit-head bytes of a
// stream: compiler errors come first, test summaries last.
type headTailBuffer struct {
head, limit int
first bytes.Buffer
tail []byte
dropped int64
}
func (b *headTailBuffer) Write(p []byte) (int, error) {
n := len(p)
if room := b.head - b.first.Len(); room > 0 {
take := min(room, len(p))
b.first.Write(p[:take])
p = p[take:]
}
if len(p) == 0 {
return n, nil
}
keep := b.limit - b.head
b.tail = append(b.tail, p...)
if over := len(b.tail) - keep; over > 0 {
b.dropped += int64(over)
b.tail = append(b.tail[:0], b.tail[over:]...)
}
return n, nil
}
// String returns the retained text and whether anything was dropped.
func (b *headTailBuffer) String() (string, bool) {
if b.dropped == 0 {
return strings.ToValidUTF8(strings.TrimRight(b.first.String()+string(b.tail), "\n"), "\uFFFD"), false
}
tail := b.tail
for len(tail) > 0 && !utf8.RuneStart(tail[0]) {
tail = tail[1:]
}
text := b.first.String() + fmt.Sprintf("\n[... %d bytes omitted ...]\n", b.dropped) + string(tail)
return strings.ToValidUTF8(strings.TrimRight(text, "\n"), "\uFFFD"), true
}
+159
View File
@@ -0,0 +1,159 @@
package stage
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func checkDefinition(t *testing.T, commands string, configs map[string]string) Definition {
t.Helper()
if configs == nil {
configs = map[string]string{}
}
return Definition{Key: "verify", Type: CheckType, Workspace: t.TempDir(),
Blocks: map[string]string{"commands": commands, "configs": "type=check", "edges": "x"},
Configs: configs,
Edges: map[string]string{"pass": "review", "fail": "implement", "error": "#failure"}}
}
func TestCheckStageValidation(t *testing.T) {
def := checkDefinition(t, "# lint first\ngo vet ./...\n\ngo test ./...", map[string]string{"command_timeout": "5m", "keep_going": "true", "timeout": "20m", "delivery": "true"})
spec, err := CheckStageSpec(def)
if err != nil {
t.Fatal(err)
}
if len(spec.Commands) != 2 || spec.CommandTimeout != 5*time.Minute || spec.Timeout != 20*time.Minute || !spec.KeepGoing || !spec.Delivery {
t.Fatalf("spec %+v", spec)
}
if err := DefaultRegistry().Validate(def); err != nil {
t.Fatal("registry:", err)
}
if enabled, err := DeliveryEnabled(def); err != nil || !enabled {
t.Fatal("delivery check", enabled, err)
}
for name, change := range map[string]func(*Definition){
"no commands": func(d *Definition) { d.Blocks["commands"] = "# only a comment\n" },
"too many": func(d *Definition) { d.Blocks["commands"] = strings.Repeat("true\n", 21) },
"prompt block": func(d *Definition) { d.Blocks["prompt"] = "Run the tests." },
"tools block": func(d *Definition) { d.Blocks["tools"] = "shell" },
"skills block": func(d *Definition) { d.Blocks["skills"] = "x" },
"unknown config": func(d *Definition) { d.Configs["model"] = "x" },
"bad timeout": func(d *Definition) { d.Configs["command_timeout"] = "soon" },
"bad keep_going": func(d *Definition) { d.Configs["keep_going"] = "yes" },
"bad delivery": func(d *Definition) { d.Configs["delivery"] = "false" },
"missing fail": func(d *Definition) { delete(d.Edges, "fail") },
"missing pass": func(d *Definition) { delete(d.Edges, "pass") },
"success outcome": func(d *Definition) { d.Edges["success"] = "#success" },
} {
t.Run(name, func(t *testing.T) {
copy := def
copy.Blocks, copy.Configs, copy.Edges = map[string]string{}, map[string]string{}, map[string]string{}
for k, v := range def.Blocks {
copy.Blocks[k] = v
}
for k, v := range def.Configs {
copy.Configs[k] = v
}
for k, v := range def.Edges {
copy.Edges[k] = v
}
change(&copy)
if err := (CheckStage{}).Validate(copy); err == nil {
t.Fatal("accepted")
}
})
}
}
func TestCheckStageRunsCommandsInTheWorkspace(t *testing.T) {
def := checkDefinition(t, "pwd > where.txt\necho all good", nil)
result, err := DefaultRegistry().Run(context.Background(), def, Values{})
if err != nil {
t.Fatal(err)
}
if result.Outcome != CheckPass {
t.Fatalf("outcome %q: %v", result.Outcome, result.Output)
}
where, _ := os.ReadFile(filepath.Join(def.Workspace, "where.txt"))
real, _ := filepath.EvalSymlinks(def.Workspace)
if got := strings.TrimSpace(string(where)); got != def.Workspace && got != real {
t.Fatalf("ran in %q, want %q", got, def.Workspace)
}
if result.Output["summary"] != "2 checks passed." {
t.Fatal("summary", result.Output["summary"])
}
checks := result.Output["checks"].([]any)
if len(checks) != 2 || checks[1].(map[string]any)["output"] != "all good" {
t.Fatalf("checks %v", checks)
}
}
func TestCheckStageFailureIsTheHandoff(t *testing.T) {
def := checkDefinition(t, "echo compiling\necho 'FAIL: TestParse expected 2' >&2; exit 3\necho never", nil)
result, err := (CheckStage{}).Run(context.Background(), def, nil)
if err != nil {
t.Fatal(err)
}
if result.Outcome != CheckFail {
t.Fatalf("outcome %q", result.Outcome)
}
markdown := result.Output["markdown"].(string)
handoff := markdown[strings.Index(markdown, "# handoff"):strings.Index(markdown, "## Commands")]
for _, want := range []string{"1 of 3 checks failed", "exit code 3", "FAIL: TestParse expected 2"} {
if !strings.Contains(handoff, want) {
t.Fatalf("handoff lacks %q:\n%s", want, handoff)
}
}
if !strings.HasPrefix(markdown, "# outcome\n\nfail\n") {
t.Fatalf("markdown does not start with the outcome:\n%s", markdown)
}
checks := result.Output["checks"].([]any)
if checks[2].(map[string]any)["status"] != CheckStatusNotRun {
t.Fatal("a later check ran after a failure", checks[2])
}
// keep_going runs every command and reports each failure.
def.Configs["keep_going"] = "true"
def.Blocks["commands"] = "exit 1\nexit 2\ntrue"
result, _ = (CheckStage{}).Run(context.Background(), def, nil)
if result.Output["summary"] != "2 of 3 checks failed: exit 1; exit 2" {
t.Fatal(result.Output["summary"])
}
}
func TestCheckStageCommandTimeoutKillsTheProcessGroup(t *testing.T) {
def := checkDefinition(t, "sleep 30 & echo started; wait", map[string]string{"command_timeout": "300ms"})
started := time.Now()
result, err := (CheckStage{}).Run(context.Background(), def, nil)
if err != nil {
t.Fatal(err)
}
if time.Since(started) > 10*time.Second {
t.Fatal("timeout did not stop the command", time.Since(started))
}
check := result.Output["checks"].([]any)[0].(map[string]any)
if result.Outcome != CheckFail || check["status"] != CheckStatusTimedOut || !strings.Contains(check["output"].(string), "command_timeout") {
t.Fatalf("result %v", check)
}
}
func TestCheckOutputIsBoundedHeadAndTail(t *testing.T) {
buffer := &headTailBuffer{head: 10, limit: 30}
for i := 0; i < 100; i++ {
_, _ = buffer.Write([]byte("0123456789"))
}
_, _ = buffer.Write([]byte("THE-END"))
text, truncated := buffer.String()
if !truncated || !strings.HasPrefix(text, "0123456789") || !strings.HasSuffix(text, "THE-END") || len(text) > 80 {
t.Fatalf("%v %q", truncated, text)
}
def := checkDefinition(t, "head -c 300000 /dev/zero | tr '\\0' x; echo; echo TAIL; exit 1", nil)
result, _ := (CheckStage{}).Run(context.Background(), def, nil)
check := result.Output["checks"].([]any)[0].(map[string]any)
if output := check["output"].(string); len(output) > maxCheckOutputBytes+200 || !strings.HasSuffix(output, "TAIL") || check["truncated"] != true {
t.Fatalf("output %d bytes, truncated %v", len(output), check["truncated"])
}
}
+31 -5
View File
@@ -131,7 +131,10 @@ func claudeMCPAllowRules(tools []string) ([]string, error) {
// approved only below the run directory and the stage's artifacts directory;
// everything else a declared tool does not need approval for stays denied by
// dontAsk.
func claudeAllowRules(tools []string, directory, artifactsDir string) []string {
//
// A non-nil shell allow-list replaces the bare Bash rule with one Bash(...)
// rule per permitted command, so any other command is refused.
func claudeAllowRules(tools []string, directory, artifactsDir string, shell []string) []string {
rules := []string{}
edit := false
for _, tool := range tools {
@@ -139,6 +142,12 @@ func claudeAllowRules(tools []string, directory, artifactsDir string) []string {
case "Edit":
edit = true
case "Write":
case "Bash":
if shell != nil {
rules = append(rules, claudeShellRules(shell)...)
} else {
rules = append(rules, tool)
}
default:
rules = append(rules, tool)
}
@@ -160,7 +169,7 @@ func (c *ClaudeStageClient) args(config ModelConfig, tools []string, effort stri
// skills block) may be loaded. A skill only adds instructions; the declared
// tools and their rules still bound what the session can do.
tools = append(append([]string(nil), tools...), "Skill")
rules := claudeAllowRules(tools, c.Directory, c.ArtifactsDir)
rules := claudeAllowRules(tools, c.Directory, c.ArtifactsDir, c.Policy.Shell)
args := []string{"-p", "--output-format", "stream-json", "--verbose",
"--model", config.Model,
"--permission-mode", "dontAsk",
@@ -212,10 +221,11 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr
if effort == "none" || effort == "minimal" {
return "", fmt.Errorf("the claude harness supports reasoning_effort low, medium, high, xhigh or max")
}
if len(c.WritePaths) > 0 || c.Policy.Edit != nil || c.Policy.Shell != nil {
if len(c.WritePaths) > 0 || c.Policy.Edit != nil {
// The other harnesses enforce these narrower scopes themselves. Claude
// Code's rule syntax is not audited for them, so refuse, never widen.
return "", fmt.Errorf("the claude harness cannot enforce a permissions block or a narrowed write scope; use the opencode harness for this stage")
// Code's edit-path rules are not audited for them, so refuse, never
// widen. A shell allow-list is enforced with Bash(...) rules.
return "", fmt.Errorf("the claude harness cannot enforce permissions.edit or a narrowed write scope; use the opencode harness for this stage")
}
tools, err := claudeTools(c.Tools)
if err != nil {
@@ -272,6 +282,11 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr
}
owned = true
}
if c.Policy.Shell != nil {
// The allow-list is enforced by Bash(...) rules; say it up front so the
// session does not spend turns on refused commands.
prompt += "\nPermitted shell commands (a trailing * allows any arguments; anything else is refused): " + strings.Join(c.Policy.Shell, "; ")
}
if text, err = c.run(ctx, env, c.args(config, tools, effort, false), config.Model, prompt); err != nil {
return "", err
}
@@ -327,6 +342,17 @@ func claudeStageEnvironment(inherited []string, artifactsDir string) []string {
// claudeConfigDir is the Claude Code configuration directory the stage's CLI
// will use: the environment's CLAUDE_CONFIG_DIR, else $HOME/.claude.
// HarnessStateDirs are directories a harness itself writes during a visit
// (Claude Code's config directory: session state, caches) for the given
// environment. When one lives inside the run directory its changes are the
// harness's, not the stage's.
func HarnessStateDirs(env []string) []string {
if dir := claudeConfigDir(env); dir != "" {
return []string{filepath.Clean(dir)}
}
return nil
}
func claudeConfigDir(env []string) string {
lookup := func(name string) string {
for i := len(env) - 1; i >= 0; i-- {
+78 -8
View File
@@ -228,6 +228,74 @@ func TestClaudeStageDeclaredToolsAreTheOnlyTools(t *testing.T) {
}
}
// A shell allow-list replaces the bare Bash rule: only the listed commands
// (exact, or a prefix with any arguments) are approved under dontAsk.
func TestClaudeStageShellAllowListMapsToBashRules(t *testing.T) {
client, root, _ := fakeClaudeClient(t, "success")
client.Tools = []string{"read", "shell"}
client.Policy.Shell = []string{"go test ./...", "git diff *"}
if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err != nil {
t.Fatal(err)
}
calls := fakeClaudeArgs(t, root)
if len(calls) != 1 {
t.Fatal(calls)
}
args := calls[0]
for _, want := range []string{"Read,Bash,Skill", "Bash(go test ./...)", "Bash(git diff:*)"} {
if !slices.Contains(args, want) {
t.Fatalf("missing %q in args %q", want, args)
}
}
if slices.Contains(args, "Bash") {
t.Fatalf("a bare Bash rule approves every command: %q", args)
}
prompt, _ := os.ReadFile(filepath.Join(root, "prompt"))
if !strings.Contains(string(prompt), "Permitted shell commands") || !strings.Contains(string(prompt), "git diff *") {
t.Fatalf("prompt does not name the allow-list: %q", prompt)
}
// An empty list approves no command at all.
client2, root2, _ := fakeClaudeClient(t, "success")
client2.Tools = []string{"shell"}
client2.Policy.Shell = []string{}
if _, err := client2.Generate(context.Background(), claudeConfig(nil), "task"); err != nil {
t.Fatal(err)
}
for _, arg := range fakeClaudeArgs(t, root2)[0] {
if strings.HasPrefix(arg, "Bash") && arg != "Bash,Skill" {
t.Fatalf("empty allow-list approved %q", arg)
}
}
}
func TestClaudeStagePermissionsValidation(t *testing.T) {
def := func(permissions string) Definition {
return Definition{Key: "review", Type: ModelType,
Blocks: map[string]string{"prompt": "Review.", "configs": "x", "tools": "read\nshell", "permissions": permissions},
Configs: map[string]string{"harness": "claude", "provider": "anthropic", "model": "claude-haiku-5-5"},
Edges: map[string]string{"success": "#success"}}
}
if _, err := (ModelStage{}).Spec(def(`{"shell":["git diff *","go test ./..."]}`)); err != nil {
t.Fatal("shell allow-list rejected:", err)
}
for name, permissions := range map[string]string{
"edit": `{"edit":["a.go"],"shell":[]}`,
"chaining": `{"shell":["go test && rm x"]}`,
"mid star": `{"shell":["git * diff"]}`,
"parentheses": `{"shell":["echo (x)"]}`,
} {
if _, err := (ModelStage{}).Spec(def(permissions)); err == nil {
t.Fatal(name, "accepted")
}
}
// Prefix entries are claude-only: other harnesses enforce exact commands.
opencode := def(`{"shell":["git diff *"]}`)
opencode.Configs = map[string]string{"provider": "opencode-go", "model": "deepseek-v4.1-flash"}
if _, err := (ModelStage{}).Spec(opencode); err == nil || !strings.Contains(err.Error(), "claude harness") {
t.Fatal("opencode prefix permission:", err)
}
}
func TestClaudeStageNamedMCPToolsAreAllowlistedSeparately(t *testing.T) {
client, root, _ := fakeClaudeClient(t, "success")
client.Tools = []string{"read", "mcp:ai-memory", "mcp:linear/list_issues"}
@@ -254,12 +322,11 @@ func TestClaudeStageNamedMCPToolsAreAllowlistedSeparately(t *testing.T) {
func TestClaudeStageRefusesWhatItCannotEnforce(t *testing.T) {
for name, change := range map[string]func(*ClaudeStageClient, *ModelConfig){
"write paths": func(c *ClaudeStageClient, _ *ModelConfig) { c.WritePaths = []string{"app"} },
"edit permissions": func(c *ClaudeStageClient, _ *ModelConfig) { c.Policy.Edit = []string{"app/**"} },
"shell permissions": func(c *ClaudeStageClient, _ *ModelConfig) { c.Policy.Shell = []string{"go test"} },
"unknown tool": func(c *ClaudeStageClient, _ *ModelConfig) { c.Tools = []string{"browser"} },
"other provider": func(_ *ClaudeStageClient, m *ModelConfig) { m.Provider = "opencode-go" },
"no reasoning": func(_ *ClaudeStageClient, m *ModelConfig) { m.ReasoningEffort = "none" },
"write paths": func(c *ClaudeStageClient, _ *ModelConfig) { c.WritePaths = []string{"app"} },
"edit permissions": func(c *ClaudeStageClient, _ *ModelConfig) { c.Policy.Edit = []string{"app/**"} },
"unknown tool": func(c *ClaudeStageClient, _ *ModelConfig) { c.Tools = []string{"browser"} },
"other provider": func(_ *ClaudeStageClient, m *ModelConfig) { m.Provider = "opencode-go" },
"no reasoning": func(_ *ClaudeStageClient, m *ModelConfig) { m.ReasoningEffort = "none" },
} {
t.Run(name, func(t *testing.T) {
client, root, active := fakeClaudeClient(t, "success")
@@ -326,7 +393,8 @@ func TestClaudeStageBudgetAccounting(t *testing.T) {
func TestClaudeStageOutcomeRepairResumesTheSameSession(t *testing.T) {
client, root, _ := fakeClaudeClient(t, "repair")
budget := NewBudget(0, 1000)
ctx := withOutputRepair(context.Background(), []string{"error", "success"})
counter := &RepairCounter{}
ctx := withOutputRepair(WithRepairCounter(context.Background(), counter), []string{"error", "success"})
text, err := client.Generate(ctx, claudeConfig(budget), "task")
if err != nil || !strings.HasPrefix(text, "# outcome\nsuccess\n") || !strings.Contains(text, "Report kept.") {
t.Fatalf("%q %v", text, err)
@@ -339,6 +407,9 @@ func TestClaudeStageOutcomeRepairResumesTheSameSession(t *testing.T) {
if budget.Snapshot().UsedTokens != 34 {
t.Fatalf("usage %+v", budget.Snapshot())
}
if counter.Count() != 1 {
t.Fatalf("repair follow-ups counted %d, want 1", counter.Count())
}
}
func TestClaudeStageTimeoutStopsTheProcessGroup(t *testing.T) {
@@ -395,7 +466,6 @@ func TestClaudeHarnessValidation(t *testing.T) {
"unknown harness": definition(map[string]string{"harness": "codex", "provider": "anthropic", "model": "claude-haiku-5-5"}, nil),
"capitalised": definition(map[string]string{"harness": "Claude", "provider": "anthropic", "model": "claude-haiku-5-5"}, nil),
"other provider": definition(claude(map[string]string{"provider": "opencode-go"}), nil),
"delivery": definition(claude(map[string]string{"delivery": "true"}), nil),
"permissions block": definition(claude(nil), map[string]string{"permissions": `{"edit":["app/**"]}`}),
"no reasoning": definition(claude(map[string]string{"reasoning_effort": "none"}), nil),
} {
+7 -5
View File
@@ -84,7 +84,7 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
}
for key := range def.Configs {
switch key {
case "provider", "model", "reasoning_effort", "retries", "timeout", "budget_usd", "budget_tokens", "harness", "delivery", "auto_skip":
case "provider", "model", "reasoning_effort", "retries", "timeout", "budget_usd", "budget_tokens", "harness", "delivery", "auto_skip", "allow_workspace_changes":
default:
return ModelSpec{}, fmt.Errorf("unknown config %q", key)
}
@@ -111,8 +111,10 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
if value := def.Configs["auto_skip"]; value != "" && value != "true" && value != "false" {
return ModelSpec{}, fmt.Errorf("auto_skip must be true or false")
}
if def.Configs["delivery"] == "true" && backend != "opencode" {
return ModelSpec{}, fmt.Errorf("delivery is supported only by the opencode harness")
// allow_workspace_changes=true lets a stage without edit leave file changes
// in the run directory; by default the runner fails such a visit.
if value := def.Configs["allow_workspace_changes"]; value != "" && value != "true" && value != "false" {
return ModelSpec{}, fmt.Errorf("allow_workspace_changes must be true or false")
}
if err := ValidateChecksBlock(def); err != nil {
return ModelSpec{}, err
@@ -143,8 +145,8 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
if _, err := claudeTools(tools); err != nil {
return ModelSpec{}, err
}
if _, present := def.Blocks["permissions"]; present {
return ModelSpec{}, fmt.Errorf("the claude harness cannot enforce a permissions block; use the opencode harness for this stage")
if err := claudePermissionsSupported(def); err != nil {
return ModelSpec{}, err
}
if effort == "none" || effort == "minimal" {
return ModelSpec{}, fmt.Errorf("the claude harness supports reasoning_effort low, medium, high, xhigh or max")
+30 -2
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"strings"
"sync/atomic"
"git.a-wan.net/alan/pipelines/internal/turn"
)
@@ -13,14 +14,38 @@ import (
// message in the same session asking only for the outcome, instead of failing
// a stage whose admitted work a full retry would repeat. The outcome is always
// stated by the model; the server never infers one from prose.
type outputRepair struct{ outcomes []string }
type outputRepair struct {
outcomes []string
counter *RepairCounter
}
type outputRepairKey struct{}
type repairCounterKey struct{}
// RepairCounter counts the outcome repair follow-ups sent during one visit
// (across its attempts). The runner records the count on the step.
type RepairCounter struct{ n atomic.Int32 }
// Count is the number of follow-ups sent so far.
func (c *RepairCounter) Count() int {
if c == nil {
return 0
}
return int(c.n.Load())
}
// WithRepairCounter makes every outcome repair follow-up under ctx increment
// counter.
func WithRepairCounter(ctx context.Context, counter *RepairCounter) context.Context {
return context.WithValue(ctx, repairCounterKey{}, counter)
}
// withOutputRepair lets a model client repair a missing or invalid outcome
// for the given declared outcomes while its session is still open.
func withOutputRepair(ctx context.Context, outcomes []string) context.Context {
return context.WithValue(ctx, outputRepairKey{}, &outputRepair{outcomes: outcomes})
counter, _ := ctx.Value(repairCounterKey{}).(*RepairCounter)
return context.WithValue(ctx, outputRepairKey{}, &outputRepair{outcomes: outcomes, counter: counter})
}
// outputRepairFrom returns the attempt's repair, or nil when none applies.
@@ -40,6 +65,9 @@ func (r *outputRepair) followUp(text string) (string, bool) {
if !errors.Is(err, turn.ErrMissingOutcome) && !errors.Is(err, turn.ErrOutcomeNotAllowed) && !errors.Is(err, turn.ErrDuplicateOutcome) {
return "", false
}
if r.counter != nil {
r.counter.n.Add(1)
}
allowed := strings.Join(r.outcomes, ", ")
return "Your final message has no valid `# outcome` section. Do not redo any work or repeat your report; the server keeps it. " +
outputShape(r.outcomes) + " Reply with only these two lines:\n\n# outcome\n<one of: " + allowed + ">\n", true
+52 -2
View File
@@ -77,9 +77,17 @@ func StagePermissions(def Definition) (ToolPolicy, error) {
seen[pattern] = true
}
seen = map[string]bool{}
claude := def.Configs["harness"] == ClaudeBackend
for _, command := range policy.Shell {
if command == "" || strings.TrimSpace(command) != command || strings.ContainsAny(command, "*?;|&<>`$\r\n\\") {
return ToolPolicy{}, fmt.Errorf("shell permissions must be exact commands without wildcards, chaining, redirects, or expansion")
exact, prefix := ShellPermissionPrefix(command)
if prefix && !claude {
return ToolPolicy{}, fmt.Errorf("shell prefix permissions (%q) are supported only by the claude harness; list exact commands", command)
}
if exact == "" || strings.TrimSpace(exact) != exact || strings.ContainsAny(exact, "*?;|&<>`$\r\n\\") {
return ToolPolicy{}, fmt.Errorf("shell permissions must be exact commands (or, on the claude harness, a command prefix ending in \" *\") without other wildcards, chaining, redirects, or expansion")
}
if claude && strings.ContainsAny(exact, "()") {
return ToolPolicy{}, fmt.Errorf("claude shell permissions cannot contain parentheses")
}
if seen[command] {
return ToolPolicy{}, fmt.Errorf("duplicate shell permission")
@@ -92,3 +100,45 @@ func StagePermissions(def Definition) (ToolPolicy, error) {
}
return *policy, nil
}
// ShellPermissionPrefix splits a permissions.shell entry. "go test *" is a
// prefix entry (the command with any arguments; claude harness only) and
// returns ("go test", true); any other entry is an exact command.
func ShellPermissionPrefix(entry string) (string, bool) {
if base, ok := strings.CutSuffix(entry, " *"); ok {
return base, true
}
return entry, false
}
// claudePermissionsSupported limits a claude stage's permissions block to a
// shell allow-list (mapped to Bash(...) rules). Claude Code's edit-path rules
// are not audited, so restricted edits stay with the other harnesses.
func claudePermissionsSupported(def Definition) error {
if _, present := def.Blocks["permissions"]; !present {
return nil
}
policy, err := StagePermissions(def)
if err != nil {
return err
}
if policy.Edit != nil {
return fmt.Errorf("the claude harness enforces only permissions.shell; remove permissions.edit or use the opencode harness for this stage")
}
return nil
}
// claudeShellRules maps a shell allow-list to Claude Code permission rules:
// an exact command to Bash(command) and a prefix entry to Bash(prefix:*).
// Claude Code checks each part of a chained command against the rules.
func claudeShellRules(shell []string) []string {
rules := make([]string, 0, len(shell))
for _, entry := range shell {
if base, prefix := ShellPermissionPrefix(entry); prefix {
rules = append(rules, "Bash("+base+":*)")
} else {
rules = append(rules, "Bash("+base+")")
}
}
return rules
}
+5 -2
View File
@@ -33,7 +33,10 @@ type Definition struct {
// ArtifactsDir is the per-run/step directory the runtime created for this
// visit; empty when the runner did not provide one (for example in tests).
ArtifactsDir string
Turn TurnPaths
// Workspace is the run directory (runtime-provided); a check stage runs
// its commands there.
Workspace string
Turn TurnPaths
// Skills is the visit's materialised skills block (runtime-provided, like
// ArtifactsDir); nil when the stage configures none or in tests.
Skills *SkillSet
@@ -72,7 +75,7 @@ func NewRegistry(types map[string]Stage) *Registry {
}
func DefaultRegistry() *Registry {
return NewRegistry(map[string]Stage{ModelType: ModelStage{}, NtfyType: NtfyStage{}, HumanType: HumanStage{}})
return NewRegistry(map[string]Stage{ModelType: ModelStage{}, NtfyType: NtfyStage{}, HumanType: HumanStage{}, CheckType: CheckStage{}})
}
func EffectiveType(name string) string {
+10 -3
View File
@@ -40,8 +40,9 @@ func (a LandingAccess) valid() bool {
}
// DeliveryEnabled is the narrow, declarative capability check used before the
// runner supplies any landing paths. Only a validated model definition can ask
// for it; runtime paths are still derived by the server.
// runner supplies any landing paths. Only a validated model or check
// definition can ask for it, whatever its harness; runtime paths are still
// derived by the server.
func DeliveryEnabled(def Definition) (bool, error) {
delivery := def.Configs["delivery"]
if delivery == "" {
@@ -50,8 +51,14 @@ func DeliveryEnabled(def Definition) (bool, error) {
if delivery != "true" {
return false, fmt.Errorf("delivery must be true when set")
}
if EffectiveType(def.Type) == CheckType {
if _, err := CheckStageSpec(def); err != nil {
return false, fmt.Errorf("invalid delivery check stage: %w", err)
}
return true, nil
}
if EffectiveType(def.Type) != ModelType {
return false, fmt.Errorf("delivery is supported only by model stages")
return false, fmt.Errorf("delivery is supported only by model and check stages")
}
if _, err := (ModelStage{}).Spec(def); err != nil {
return false, fmt.Errorf("invalid delivery model stage: %w", err)
+19 -10
View File
@@ -246,18 +246,27 @@ func TestDeliveryEnabledRequiresValidatedModelStage(t *testing.T) {
}
}
func TestDeliveryRejectsPiBeforeAgentExecution(t *testing.T) {
func TestDeliveryIsHarnessAgnostic(t *testing.T) {
for _, harness := range []string{"opencode", "pi"} {
def := modelDefinition()
def.Configs["delivery"] = "true"
def.Configs["harness"] = harness
def.Blocks["checks"] = "go test ./..."
if err := (ModelStage{}).Validate(def); err != nil {
t.Fatalf("%s delivery was rejected: %v", harness, err)
}
if enabled, err := DeliveryEnabled(def); err != nil || !enabled {
t.Fatalf("%s delivery = %v, %v", harness, enabled, err)
}
}
def := modelDefinition()
def.Configs["delivery"] = "true"
def.Configs["harness"] = "pi"
def.Blocks["checks"] = "true"
if err := (ModelStage{}).Validate(def); err == nil || !strings.Contains(err.Error(), "opencode harness") {
t.Fatal("Pi delivery was accepted", err)
}
delete(def.Configs, "delivery")
delete(def.Blocks, "checks")
if err := (ModelStage{}).Validate(def); err != nil {
t.Fatal("Pi non-delivery was changed", err)
def.Configs["harness"] = ClaudeBackend
def.Configs["provider"] = ClaudeProvider
def.Configs["model"] = "claude-sonnet-4-5"
def.Blocks["checks"] = "go test ./..."
if enabled, err := DeliveryEnabled(def); err != nil || !enabled {
t.Fatalf("claude delivery = %v, %v", enabled, err)
}
}