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 }