Runs park on usage limits; failure classes, harness error policy, run budgets
- A stage refused for a Claude usage limit no longer fails its run: the runner tries the chats' Claude account auto-switch (per-home setting) and reruns the visit, else parks the run in the new waiting_quota status (persisted, with reset/resume time in run summaries, details and events) and resumes the same visit at reset + 1 min, also after a restart. resume_run / `pipelines resume` resumes now; cancel works on parked runs. The rerun visit gets a "# Previous attempt" interruption note. Subscription limits no longer say "top up the provider account". - run/retry into an account known to be limited are deferred (quota_policy defer/refuse/now; CLI refuses under --json/--yes unless --defer or --now). - failure_class on runs (quota, loop_exhausted, timeout, permission_denied, harness_error, blocked, environment, canceled, interrupted, budget, check_failed, other) in RunSummary/RunDetail/events, CLI inspect/runs/wait/ stats and the app failure line. - Claude permission denials (permission_denials / refused tool results) fail a blocked visit with permission_denied naming the tool use. - Harness failures are classified transient vs deterministic; deterministic ones (and a repeated empty readback) skip error self-loops; transient self-loops back off 15 s, 1 min, 4 min. - Whole-run USD budget: run --budget, server default (run-budget / get/set_run_settings); 80% warning notification, stop with class budget. - App: waiting_quota status/filter with resume time, Resume now and Cancel, failure class wording. Docs and skill references updated. Merges main (check stage, delivery gate, Claude stage restart survival, schedule changes). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+101
-3
@@ -90,6 +90,8 @@ type reportedUsage struct {
|
||||
}
|
||||
|
||||
type Budget struct {
|
||||
// run is the whole-run cap this stage budget also counts towards.
|
||||
run *RunBudget
|
||||
mu sync.Mutex
|
||||
state BudgetSnapshot
|
||||
records map[string]BudgetSnapshot
|
||||
@@ -108,6 +110,22 @@ func (b *Budget) RestoreUsage(used BudgetSnapshot) {
|
||||
used.LimitUSD, used.LimitTokens = b.state.LimitUSD, b.state.LimitTokens
|
||||
b.state = used
|
||||
}
|
||||
|
||||
// SetRun makes the stage budget count its cost towards the whole-run cap.
|
||||
func (b *Budget) SetRun(run *RunBudget) { b.mu.Lock(); b.run = run; b.mu.Unlock() }
|
||||
|
||||
// watched reports whether a harness must poll usage: a stage limit or a
|
||||
// whole-run cap is set.
|
||||
func (b *Budget) watched() bool {
|
||||
if b == nil {
|
||||
return false
|
||||
}
|
||||
b.mu.Lock()
|
||||
run := b.run
|
||||
b.mu.Unlock()
|
||||
return b.Enabled() || run.Enabled()
|
||||
}
|
||||
|
||||
func (b *Budget) Enabled() bool { return b != nil && (b.state.LimitUSD > 0 || b.state.LimitTokens > 0) }
|
||||
func (b *Budget) Snapshot() BudgetSnapshot { b.mu.Lock(); defer b.mu.Unlock(); return b.state }
|
||||
|
||||
@@ -154,13 +172,21 @@ func (b *Budget) checkLocked() error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (b *Budget) Check() error { b.mu.Lock(); defer b.mu.Unlock(); return b.checkLocked() }
|
||||
func (b *Budget) Check() error {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if err := b.checkLocked(); err != nil {
|
||||
return err
|
||||
}
|
||||
return b.run.Check()
|
||||
}
|
||||
|
||||
func (b *Budget) observe(key string, usage reportedUsage) error {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
old := b.records[key]
|
||||
defer func() { b.records[key] = old }()
|
||||
spentBefore := b.state.UsedUSD
|
||||
if usage.USD != nil {
|
||||
if *usage.USD < 0 || math.IsNaN(*usage.USD) || math.IsInf(*usage.USD, 0) {
|
||||
return fmt.Errorf("%w: invalid cost", ErrBudgetAccounting)
|
||||
@@ -231,7 +257,68 @@ func (b *Budget) observe(key string, usage reportedUsage) error {
|
||||
case b.state.LimitTokens > 0:
|
||||
return fmt.Errorf("%w: complete token usage was not reported", ErrBudgetAccounting)
|
||||
}
|
||||
return b.checkLocked()
|
||||
if err := b.checkLocked(); err != nil {
|
||||
return err
|
||||
}
|
||||
return b.run.add(b.state.UsedUSD - spentBefore)
|
||||
}
|
||||
|
||||
// RunBudget is a run's whole-run USD cap, shared by every stage budget of
|
||||
// the run. A nil or zero-limit RunBudget only counts.
|
||||
type RunBudget struct {
|
||||
mu sync.Mutex
|
||||
limit float64
|
||||
spent float64
|
||||
}
|
||||
|
||||
// NewRunBudget starts a run cap of limit USD (0 = none) with spent already
|
||||
// used by earlier visits.
|
||||
func NewRunBudget(limit, spent float64) *RunBudget {
|
||||
return &RunBudget{limit: limit, spent: spent}
|
||||
}
|
||||
|
||||
func (r *RunBudget) Enabled() bool { return r != nil && r.limit > 0 }
|
||||
|
||||
// Spent and Limit report the cap's state.
|
||||
func (r *RunBudget) Spent() float64 {
|
||||
if r == nil {
|
||||
return 0
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return r.spent
|
||||
}
|
||||
|
||||
func (r *RunBudget) Limit() float64 {
|
||||
if r == nil {
|
||||
return 0
|
||||
}
|
||||
return r.limit
|
||||
}
|
||||
|
||||
func (r *RunBudget) add(usd float64) error {
|
||||
if r == nil {
|
||||
return nil
|
||||
}
|
||||
r.mu.Lock()
|
||||
if usd > 0 {
|
||||
r.spent += usd
|
||||
}
|
||||
r.mu.Unlock()
|
||||
return r.Check()
|
||||
}
|
||||
|
||||
// Check fails with ErrRunBudgetExceeded once the run spent its cap.
|
||||
func (r *RunBudget) Check() error {
|
||||
if !r.Enabled() {
|
||||
return nil
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.spent >= r.limit {
|
||||
return fmt.Errorf("%w: %w: USD %.2f / %.2f", ErrBudgetExceeded, ErrRunBudgetExceeded, r.spent, r.limit)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type budgetContextKey struct{}
|
||||
@@ -239,6 +326,17 @@ type budgetContextKey struct{}
|
||||
func WithBudget(ctx context.Context, budget *Budget) context.Context {
|
||||
return context.WithValue(ctx, budgetContextKey{}, budget)
|
||||
}
|
||||
|
||||
// BudgetFrom is the stage budget a visit runs under (nil when none); an
|
||||
// in-process executor reports its cost with ObserveCost.
|
||||
func BudgetFrom(ctx context.Context) *Budget { return budgetFromContext(ctx) }
|
||||
|
||||
// ObserveCost reports a session's cumulative USD cost, as a harness usage
|
||||
// report does, and fails once the stage or run cap is spent.
|
||||
func (b *Budget) ObserveCost(session string, usd float64) error {
|
||||
return b.observe(session, reportedUsage{USD: &usd})
|
||||
}
|
||||
|
||||
func budgetFromContext(ctx context.Context) *Budget {
|
||||
b, _ := ctx.Value(budgetContextKey{}).(*Budget)
|
||||
return b
|
||||
@@ -254,7 +352,7 @@ type budgetWatch struct {
|
||||
func (c OpenCodeClient) BudgetCapable() bool { return true }
|
||||
|
||||
func (c OpenCodeClient) watchBudget(ctx context.Context, budget *Budget, id string) (context.Context, *budgetWatch, error) {
|
||||
if !budget.Enabled() {
|
||||
if !budget.watched() {
|
||||
return ctx, nil, nil
|
||||
}
|
||||
if err := budget.Check(); err != nil {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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(©)
|
||||
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"])
|
||||
}
|
||||
}
|
||||
+597
-141
@@ -8,6 +8,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
@@ -16,7 +17,6 @@ import (
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/claude"
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"git.a-wan.net/alan/pipelines/internal/workenv"
|
||||
)
|
||||
|
||||
@@ -36,6 +36,9 @@ var (
|
||||
errClaudeMissing = errors.New("Claude Code is not installed on the execution server; run pipelines harness setup claude there")
|
||||
errClaudeSignedOut = errors.New("Claude Code is not signed in on the execution server; run pipelines harness setup claude there")
|
||||
errClaudeNoResult = errors.New("Claude Code ended without a final result")
|
||||
// errClaudeStoppedUnwatched: the CLI ended while no server was watching
|
||||
// it (the server was restarting) and left no final result.
|
||||
errClaudeStoppedUnwatched = errors.New("Claude Code stopped while the server was restarting, before it reported a final result")
|
||||
)
|
||||
|
||||
// ClaudeStageClient runs one stage visit with the Claude Code CLI in print
|
||||
@@ -64,6 +67,8 @@ type ClaudeStageClient struct {
|
||||
operatorPlugins []string
|
||||
|
||||
budget *Budget
|
||||
// denials are the tool uses the permission rules refused this visit.
|
||||
denials []string
|
||||
// Session totals across the visit's invocations (the prompt and one
|
||||
// outcome follow-up share a session and report per invocation).
|
||||
usd float64
|
||||
@@ -131,7 +136,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 +147,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 +174,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",
|
||||
@@ -196,7 +210,12 @@ func (c *ClaudeStageClient) args(config ModelConfig, tools []string, effort stri
|
||||
}
|
||||
|
||||
func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, prompt string) (text string, err error) {
|
||||
// A re-adopted visit was admitted by a previous server process (see
|
||||
// WithResumeSession): follow its CLI or read what it left, never prompt
|
||||
// again.
|
||||
resume := TakeResumeSession(ctx)
|
||||
c.WorkStarted = false
|
||||
c.denials = nil
|
||||
c.usd, c.input, c.output, c.reasoning, c.cacheRead, c.cacheW = 0, 0, 0, 0, 0, 0
|
||||
c.budget = config.Budget
|
||||
if c.budget == nil {
|
||||
@@ -212,10 +231,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 {
|
||||
@@ -230,34 +250,54 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr
|
||||
if _, statErr := os.Stat(c.Executable); statErr != nil {
|
||||
return "", fmt.Errorf("%w: %w", ErrHarnessUnreachable, errClaudeMissing)
|
||||
}
|
||||
cache, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
root := filepath.Join(cache, "pipelines", claudeStageSessions)
|
||||
if err = os.MkdirAll(root, 0700); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if c.Reference, err = os.MkdirTemp(root, "stage-*"); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if c.SessionID, err = newClaudeSessionID(); err != nil {
|
||||
return "", err
|
||||
var adopted *claudeStageOwner
|
||||
if resume != "" {
|
||||
owner, ownerErr := claudeStageOwnerAt(c.Reference)
|
||||
if ownerErr != nil || owner.SessionID != resume || owner.Output == "" {
|
||||
return "", fmt.Errorf("retained Claude Code stage session %.64s cannot be re-adopted: invalid retained evidence", RedactEvidence(resume))
|
||||
}
|
||||
adopted = &owner
|
||||
c.SessionID = resume
|
||||
} else {
|
||||
cache, cacheErr := os.UserCacheDir()
|
||||
if cacheErr != nil {
|
||||
return "", cacheErr
|
||||
}
|
||||
root := filepath.Join(cache, "pipelines", claudeStageSessions)
|
||||
if err = os.MkdirAll(root, 0700); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if c.Reference, err = os.MkdirTemp(root, "stage-*"); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if c.SessionID, err = newClaudeSessionID(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
env := claudeStageEnvironment(c.environment(ctx), c.ArtifactsDir)
|
||||
// User settings are not loaded, so the operator's skills are offered as
|
||||
// skills-only plugins generated for this visit, never their plugins.
|
||||
if c.operatorPlugins, err = writeOperatorSkillPlugins(filepath.Join(c.Reference, "operator-skills"), OperatorSkills(claudeConfigDir(env))); err != nil {
|
||||
// skills-only plugins generated for this visit, never their plugins. A
|
||||
// re-adopted visit keeps the ones its first process generated.
|
||||
if adopted != nil {
|
||||
c.operatorPlugins = existingOperatorSkillPlugins(filepath.Join(c.Reference, "operator-skills"))
|
||||
} else if c.operatorPlugins, err = writeOperatorSkillPlugins(filepath.Join(c.Reference, "operator-skills"), OperatorSkills(claudeConfigDir(env))); err != nil {
|
||||
return "", err
|
||||
}
|
||||
owned := false
|
||||
defer func() {
|
||||
// Quiescence is proven per invocation (see run); only then is the
|
||||
if errors.Is(err, ErrDetached) {
|
||||
// The server is stopping: the CLI keeps running and its
|
||||
// ownership stays recorded for the next process to re-adopt.
|
||||
text = ""
|
||||
return
|
||||
}
|
||||
// Quiescence is proven per invocation (see settle); only then is the
|
||||
// evidence marked settled and ownership released.
|
||||
if errors.Is(err, ErrStageCleanup) {
|
||||
text = ""
|
||||
return
|
||||
}
|
||||
c.removeRawOutput()
|
||||
_ = os.WriteFile(filepath.Join(c.Reference, "quiescent"), []byte("quiescent"), 0600)
|
||||
if owned {
|
||||
if saveErr := c.OnOwnership(c.SessionID, c.Reference, false); saveErr != nil {
|
||||
@@ -272,13 +312,26 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr
|
||||
}
|
||||
owned = true
|
||||
}
|
||||
if text, err = c.run(ctx, env, c.args(config, tools, effort, false), config.Model, prompt); err != nil {
|
||||
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 adopted != nil {
|
||||
// The prompt was admitted by the previous process. The evidence stream
|
||||
// is rebuilt from the CLI's own output, so nothing is listed twice.
|
||||
c.WorkStarted = true
|
||||
if err = os.WriteFile(filepath.Join(c.Reference, "stream.jsonl"), nil, 0600); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
if text, err = c.invoke(ctx, env, c.args(config, tools, effort, false), 0, config.Model, prompt, adopted); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// One outcome repair follow-up in the same session.
|
||||
repair := outputRepairFrom(ctx)
|
||||
if message, ok := repair.followUp(text); ok {
|
||||
reply, err := c.run(ctx, env, c.args(config, tools, effort, true), config.Model, message)
|
||||
reply, err := c.invoke(ctx, env, c.args(config, tools, effort, true), 1, config.Model, message, adopted)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -327,6 +380,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-- {
|
||||
@@ -380,149 +444,473 @@ type claudeStreamRecord struct {
|
||||
ResetsAt int64 `json:"resetsAt"`
|
||||
} `json:"rate_limit_info"`
|
||||
Message *struct {
|
||||
Error string `json:"error"`
|
||||
Error string `json:"error"`
|
||||
Content json.RawMessage `json:"content"`
|
||||
} `json:"message"`
|
||||
// PermissionDenials are the tool uses the permission rules refused
|
||||
// during the invocation (on the result record).
|
||||
PermissionDenials []claudePermissionDenial `json:"permission_denials"`
|
||||
}
|
||||
|
||||
func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model, prompt string) (text string, err error) {
|
||||
type claudePermissionDenial struct {
|
||||
ToolName string `json:"tool_name"`
|
||||
ToolInput map[string]any `json:"tool_input"`
|
||||
}
|
||||
|
||||
// maxReportedDenials bounds the denials named in a diagnostic.
|
||||
const maxReportedDenials = 5
|
||||
|
||||
// describe names a denied tool use for the operator: the tool and the path
|
||||
// or the start of the command it was refused for (bounded, one line).
|
||||
func (d claudePermissionDenial) describe() string {
|
||||
name := sanitizedClaudeName(d.ToolName)
|
||||
target := ""
|
||||
for _, key := range []string{"file_path", "path", "notebook_path", "command", "url", "pattern"} {
|
||||
if value, ok := d.ToolInput[key].(string); ok && strings.TrimSpace(value) != "" {
|
||||
target = strings.Join(strings.Fields(value), " ")
|
||||
break
|
||||
}
|
||||
}
|
||||
if target == "" {
|
||||
return name
|
||||
}
|
||||
if len([]rune(target)) > 80 {
|
||||
target = string([]rune(target)[:80]) + "..."
|
||||
}
|
||||
return name + "(" + target + ")"
|
||||
}
|
||||
|
||||
// PermissionDenials names the tool uses the visit's permission rules refused.
|
||||
func (c *ClaudeStageClient) PermissionDenials() []string { return c.denials }
|
||||
|
||||
func (c *ClaudeStageClient) noteDenial(description string) {
|
||||
for _, seen := range c.denials {
|
||||
if seen == description {
|
||||
return
|
||||
}
|
||||
}
|
||||
if len(c.denials) < maxReportedDenials {
|
||||
c.denials = append(c.denials, description)
|
||||
}
|
||||
}
|
||||
|
||||
// claudePermissionRefusal matches the tool_result text Claude Code returns for
|
||||
// a tool use its permission mode refused.
|
||||
func claudePermissionRefusal(text string) bool {
|
||||
lower := strings.ToLower(text)
|
||||
return strings.Contains(lower, "requested permissions to") || (strings.Contains(lower, "permission") && strings.Contains(lower, "denied"))
|
||||
}
|
||||
|
||||
// toolResultDenials scans a user message's tool results for permission
|
||||
// refusals of the tool uses named in uses (tool_use id -> description).
|
||||
func toolResultDenials(content json.RawMessage, uses map[string]string) []string {
|
||||
var blocks []struct {
|
||||
Type string `json:"type"`
|
||||
ToolUseID string `json:"tool_use_id"`
|
||||
IsError bool `json:"is_error"`
|
||||
Content json.RawMessage `json:"content"`
|
||||
}
|
||||
if json.Unmarshal(content, &blocks) != nil {
|
||||
return nil
|
||||
}
|
||||
var denied []string
|
||||
for _, block := range blocks {
|
||||
if block.Type != "tool_result" || !block.IsError {
|
||||
continue
|
||||
}
|
||||
var text string
|
||||
if json.Unmarshal(block.Content, &text) != nil {
|
||||
var parts []struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
_ = json.Unmarshal(block.Content, &parts)
|
||||
for _, part := range parts {
|
||||
text += part.Text
|
||||
}
|
||||
}
|
||||
if claudePermissionRefusal(text) {
|
||||
name := uses[block.ToolUseID]
|
||||
if name == "" {
|
||||
name = "a tool"
|
||||
}
|
||||
denied = append(denied, name)
|
||||
}
|
||||
}
|
||||
return denied
|
||||
}
|
||||
|
||||
// toolUses records the tool_use blocks of an assistant message.
|
||||
func toolUses(content json.RawMessage, uses map[string]string) {
|
||||
var blocks []struct {
|
||||
Type string `json:"type"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Input map[string]any `json:"input"`
|
||||
}
|
||||
if json.Unmarshal(content, &blocks) != nil {
|
||||
return
|
||||
}
|
||||
for _, block := range blocks {
|
||||
if block.Type == "tool_use" && block.ID != "" && len(uses) < 4096 {
|
||||
uses[block.ID] = claudePermissionDenial{ToolName: block.Name, ToolInput: block.Input}.describe()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// claudeInvocation is what one CLI invocation's stream-json output reported.
|
||||
type claudeInvocation struct {
|
||||
final *claudeStreamRecord
|
||||
refusal, limited bool
|
||||
resetsAt int64
|
||||
authFailed, sessionMismatch, modelMismatch bool
|
||||
// uses names the invocation's tool_use blocks (id -> description) and
|
||||
// denials the uses the permission rules refused.
|
||||
uses map[string]string
|
||||
denials []string
|
||||
}
|
||||
|
||||
func (inv *claudeInvocation) observe(record claudeStreamRecord, session, model string) {
|
||||
switch record.Type {
|
||||
case "system":
|
||||
if record.Subtype == "init" {
|
||||
inv.sessionMismatch = record.SessionID != session
|
||||
inv.modelMismatch = record.Model != model
|
||||
}
|
||||
case "rate_limit_event":
|
||||
if record.RateLimit != nil && record.RateLimit.Status == "rejected" {
|
||||
inv.limited = true
|
||||
inv.resetsAt = record.RateLimit.ResetsAt
|
||||
}
|
||||
case "user":
|
||||
if record.Message != nil {
|
||||
inv.denials = append(inv.denials, toolResultDenials(record.Message.Content, inv.uses)...)
|
||||
}
|
||||
case "assistant":
|
||||
if record.Message != nil {
|
||||
if inv.uses == nil {
|
||||
inv.uses = map[string]string{}
|
||||
}
|
||||
toolUses(record.Message.Content, inv.uses)
|
||||
switch record.Message.Error {
|
||||
case "billing_error":
|
||||
inv.refusal = true
|
||||
case "rate_limit":
|
||||
inv.refusal, inv.limited = true, true
|
||||
case "authentication_failed":
|
||||
inv.authFailed = true
|
||||
}
|
||||
}
|
||||
switch record.Error {
|
||||
case "billing_error":
|
||||
inv.refusal = true
|
||||
case "rate_limit":
|
||||
inv.refusal, inv.limited = true, true
|
||||
case "authentication_failed":
|
||||
inv.authFailed = true
|
||||
}
|
||||
case "result":
|
||||
copied := record
|
||||
inv.final = &copied
|
||||
for _, denial := range record.PermissionDenials {
|
||||
inv.denials = append(inv.denials, denial.describe())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// claudeProcess is one invocation's CLI: a child this process started, or one
|
||||
// a previous server process left (adopted: it cannot be waited on and its exit
|
||||
// status is unknown).
|
||||
type claudeProcess struct {
|
||||
pid int
|
||||
adopted bool
|
||||
done chan struct{} // closed once the CLI has exited
|
||||
waitErr error // the child's exit error, read after done
|
||||
stop chan struct{} // ends an adopted process's liveness poll
|
||||
}
|
||||
|
||||
// exitedClaudeProcess is an invocation whose CLI already exited: its output
|
||||
// is read to the end, nothing is waited for.
|
||||
func exitedClaudeProcess(pid int) *claudeProcess {
|
||||
p := &claudeProcess{pid: pid, adopted: true, done: make(chan struct{}), stop: make(chan struct{})}
|
||||
close(p.done)
|
||||
return p
|
||||
}
|
||||
|
||||
// adoptClaudeProcess follows a CLI left running by a previous server process.
|
||||
func adoptClaudeProcess(pid int, session string) *claudeProcess {
|
||||
p := &claudeProcess{pid: pid, adopted: true, done: make(chan struct{}), stop: make(chan struct{})}
|
||||
go func() {
|
||||
ticker := time.NewTicker(claudeAdoptPoll)
|
||||
defer ticker.Stop()
|
||||
for claudeProcessAlive(pid, session) {
|
||||
select {
|
||||
case <-p.stop:
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
close(p.done)
|
||||
}()
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *claudeProcess) release() {
|
||||
select {
|
||||
case <-p.stop:
|
||||
default:
|
||||
close(p.stop)
|
||||
}
|
||||
}
|
||||
|
||||
// claudeAdoptPoll is how often an adopted CLI's liveness is checked, and how
|
||||
// often its output file is read again when no new line has arrived.
|
||||
var claudeAdoptPoll = 100 * time.Millisecond
|
||||
|
||||
// claudeOutputName is the raw stdout file of invocation n in the evidence
|
||||
// directory. The CLI writes it directly, so it keeps writing whether or not a
|
||||
// server is reading; it is removed once the visit settles.
|
||||
func claudeOutputName(n int) string { return fmt.Sprintf("cli-%d.out", n) }
|
||||
|
||||
func claudePromptName(n int) string { return fmt.Sprintf("cli-%d.prompt", n) }
|
||||
|
||||
// removeRawOutput drops the unredacted CLI output and prompt files of a settled
|
||||
// visit; the redacted stream.jsonl stays as its evidence.
|
||||
func (c *ClaudeStageClient) removeRawOutput() {
|
||||
for n := 0; n < 2; n++ {
|
||||
_ = os.Remove(filepath.Join(c.Reference, claudeOutputName(n)))
|
||||
_ = os.Remove(filepath.Join(c.Reference, claudePromptName(n)))
|
||||
}
|
||||
}
|
||||
|
||||
// invoke runs invocation n (0 is the prompt, 1 the outcome repair follow-up).
|
||||
// For a re-adopted visit (adopted != nil), an invocation the previous process
|
||||
// already started is followed instead: its CLI if it still runs, else the
|
||||
// output it left. A prompt that ended without a result while no server was
|
||||
// watching is never sent again; a lost repair follow-up is.
|
||||
func (c *ClaudeStageClient) invoke(ctx context.Context, env, args []string, n int, model, prompt string, adopted *claudeStageOwner) (string, error) {
|
||||
if adopted != nil && n <= adopted.Invocation {
|
||||
var proc *claudeProcess
|
||||
switch {
|
||||
case n < adopted.Invocation:
|
||||
// An earlier invocation settled before the next one started;
|
||||
// the owner record names only the latest process.
|
||||
proc = exitedClaudeProcess(0)
|
||||
case claudeProcessAlive(adopted.PID, c.SessionID):
|
||||
proc = adoptClaudeProcess(adopted.PID, c.SessionID)
|
||||
default:
|
||||
proc = exitedClaudeProcess(adopted.PID)
|
||||
}
|
||||
inv, waitErr, err := c.follow(ctx, proc, n, model)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if inv.final != nil || n == 0 || n < adopted.Invocation {
|
||||
return c.settle(ctx, proc, inv, waitErr)
|
||||
}
|
||||
// The repair follow-up's CLI ended without a reply while the server
|
||||
// was down; the follow-up only asks for the outcome, so ask again.
|
||||
}
|
||||
proc, err := c.start(env, args, n, prompt)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
inv, waitErr, err := c.follow(ctx, proc, n, model)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return c.settle(ctx, proc, inv, waitErr)
|
||||
}
|
||||
|
||||
// start launches one CLI invocation detached from the server process: in its
|
||||
// own session, with the prompt read from a file and stdout written straight to
|
||||
// a file, so a server restart neither signals it nor cuts its output. The owner
|
||||
// record names the process and its output for a later server to re-adopt.
|
||||
func (c *ClaudeStageClient) start(env, args []string, n int, prompt string) (*claudeProcess, error) {
|
||||
promptPath := filepath.Join(c.Reference, claudePromptName(n))
|
||||
if err := os.WriteFile(promptPath, []byte(prompt), 0600); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stdin, err := os.Open(promptPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer stdin.Close()
|
||||
stdout, err := os.OpenFile(filepath.Join(c.Reference, claudeOutputName(n)), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer stdout.Close()
|
||||
stderr, err := os.OpenFile(filepath.Join(c.Reference, "stderr.log"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer stderr.Close()
|
||||
cmd := exec.Command(c.Executable, args...)
|
||||
cmd.Dir = c.Directory
|
||||
cmd.Env = env
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
cmd.Stdin = strings.NewReader(prompt)
|
||||
stderr, err := os.OpenFile(filepath.Join(c.Reference, "stderr.log"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer stderr.Close()
|
||||
cmd.Stderr = stderr
|
||||
out, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
stream, err := os.OpenFile(filepath.Join(c.Reference, "stream.jsonl"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer stream.Close()
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
|
||||
cmd.Stdin, cmd.Stdout, cmd.Stderr = stdin, stdout, stderr
|
||||
if err = cmd.Start(); err != nil {
|
||||
return "", fmt.Errorf("%w: %w", ErrHarnessUnreachable, errClaudeMissing)
|
||||
return nil, fmt.Errorf("%w: %w", ErrHarnessUnreachable, errClaudeMissing)
|
||||
}
|
||||
owner, _ := json.Marshal(map[string]any{"pid": cmd.Process.Pid, "session_id": c.SessionID})
|
||||
if err = os.WriteFile(filepath.Join(c.Reference, "owner.json"), owner, 0600); err != nil {
|
||||
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
||||
_ = cmd.Wait()
|
||||
return "", err
|
||||
proc := &claudeProcess{pid: cmd.Process.Pid, done: make(chan struct{}), stop: make(chan struct{})}
|
||||
go func() {
|
||||
// Reaps the child, also after this server detached from it.
|
||||
proc.waitErr = cmd.Wait()
|
||||
close(proc.done)
|
||||
}()
|
||||
owner := claudeStageOwner{PID: proc.pid, PGID: proc.pid, SessionID: c.SessionID, Invocation: n, Output: claudeOutputName(n)}
|
||||
if err = writeClaudeStageOwner(c.Reference, owner); err != nil {
|
||||
_ = syscall.Kill(-proc.pid, syscall.SIGKILL)
|
||||
<-proc.done
|
||||
return nil, err
|
||||
}
|
||||
// The prompt is admitted once the process has it: tool work may follow.
|
||||
c.WorkStarted = true
|
||||
var final *claudeStreamRecord
|
||||
var refusal, limited bool
|
||||
var resetsAt int64
|
||||
var authFailed, sessionMismatch, modelMismatch bool
|
||||
scanned := make(chan error, 1)
|
||||
go func() {
|
||||
scanner := bufio.NewScanner(out)
|
||||
scanner.Buffer(make([]byte, 64<<10), 16<<20)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Bytes()
|
||||
var record claudeStreamRecord
|
||||
if json.Unmarshal(line, &record) != nil {
|
||||
continue
|
||||
}
|
||||
// One valid JSON record per line: the export parses this stream.
|
||||
redacted := RedactEvidenceJSON(line)
|
||||
_, _ = stream.WriteString(redacted + "\n")
|
||||
if len(c.Transcript) < 32<<10 {
|
||||
c.Transcript += redacted + "\n"
|
||||
}
|
||||
switch record.Type {
|
||||
case "system":
|
||||
if record.Subtype == "init" {
|
||||
sessionMismatch = record.SessionID != c.SessionID
|
||||
modelMismatch = record.Model != model
|
||||
}
|
||||
case "rate_limit_event":
|
||||
if record.RateLimit != nil && record.RateLimit.Status == "rejected" {
|
||||
limited = true
|
||||
resetsAt = record.RateLimit.ResetsAt
|
||||
}
|
||||
case "assistant":
|
||||
if record.Message != nil {
|
||||
switch record.Message.Error {
|
||||
case "billing_error", "rate_limit":
|
||||
refusal = true
|
||||
case "authentication_failed":
|
||||
authFailed = true
|
||||
}
|
||||
}
|
||||
switch record.Error {
|
||||
case "billing_error", "rate_limit":
|
||||
refusal = true
|
||||
case "authentication_failed":
|
||||
authFailed = true
|
||||
}
|
||||
case "result":
|
||||
copied := record
|
||||
final = &copied
|
||||
}
|
||||
}
|
||||
scanned <- scanner.Err()
|
||||
}()
|
||||
waited := make(chan error, 1)
|
||||
go func() {
|
||||
scanErr := <-scanned
|
||||
waitErr := cmd.Wait()
|
||||
if scanErr != nil && waitErr == nil {
|
||||
waitErr = scanErr
|
||||
}
|
||||
waited <- waitErr
|
||||
}()
|
||||
var waitErr error
|
||||
select {
|
||||
case waitErr = <-waited:
|
||||
case <-ctx.Done():
|
||||
// Timeout or cancellation: stop the whole process group, then prove it.
|
||||
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM)
|
||||
select {
|
||||
case <-waited:
|
||||
case <-time.After(5 * time.Second):
|
||||
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
||||
<-waited
|
||||
}
|
||||
waitErr = ctx.Err()
|
||||
return proc, nil
|
||||
}
|
||||
|
||||
// follow reads invocation n's output file from its start until the CLI has
|
||||
// exited and every line it wrote is read, keeping the redacted evidence
|
||||
// stream. A server shutdown leaves the CLI running (ErrDetached); any other
|
||||
// cancellation stops its process group first.
|
||||
func (c *ClaudeStageClient) follow(ctx context.Context, proc *claudeProcess, n int, model string) (inv claudeInvocation, waitErr error, err error) {
|
||||
defer proc.release()
|
||||
out, err := os.Open(filepath.Join(c.Reference, claudeOutputName(n)))
|
||||
if err != nil {
|
||||
return inv, nil, err
|
||||
}
|
||||
defer out.Close()
|
||||
stream, err := os.OpenFile(filepath.Join(c.Reference, "stream.jsonl"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
|
||||
if err != nil {
|
||||
return inv, nil, err
|
||||
}
|
||||
defer stream.Close()
|
||||
consume := func(line []byte) {
|
||||
var record claudeStreamRecord
|
||||
if json.Unmarshal(line, &record) != nil {
|
||||
return
|
||||
}
|
||||
// One valid JSON record per line: the export parses this stream.
|
||||
redacted := RedactEvidenceJSON(line)
|
||||
_, _ = stream.WriteString(redacted + "\n")
|
||||
if len(c.Transcript) < 32<<10 {
|
||||
c.Transcript += redacted + "\n"
|
||||
}
|
||||
inv.observe(record, c.SessionID, model)
|
||||
}
|
||||
reader := bufio.NewReaderSize(out, 64<<10)
|
||||
var partial []byte
|
||||
exited := false
|
||||
ticker := time.NewTicker(claudeAdoptPoll)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
chunk, readErr := reader.ReadBytes('\n')
|
||||
partial = append(partial, chunk...)
|
||||
if readErr == nil {
|
||||
consume(partial)
|
||||
partial = partial[:0]
|
||||
continue
|
||||
}
|
||||
if readErr != io.EOF {
|
||||
return inv, nil, readErr
|
||||
}
|
||||
if exited {
|
||||
if len(bytes.TrimSpace(partial)) > 0 {
|
||||
consume(partial)
|
||||
}
|
||||
if !proc.adopted {
|
||||
waitErr = proc.waitErr
|
||||
}
|
||||
return inv, waitErr, nil
|
||||
}
|
||||
select {
|
||||
case <-proc.done:
|
||||
exited = true // Read what it wrote before exiting.
|
||||
case <-ticker.C:
|
||||
case <-ctx.Done():
|
||||
if Detached(ctx) {
|
||||
return inv, nil, fmt.Errorf("%w: Claude Code stage session %s left running", ErrDetached, c.SessionID)
|
||||
}
|
||||
// Timeout or cancellation: stop the whole process group, then prove it.
|
||||
if proc.pid > 1 {
|
||||
_ = syscall.Kill(-proc.pid, syscall.SIGTERM)
|
||||
}
|
||||
select {
|
||||
case <-proc.done:
|
||||
case <-time.After(5 * time.Second):
|
||||
_ = syscall.Kill(-proc.pid, syscall.SIGKILL) // done never stays open for pid 0.
|
||||
select {
|
||||
case <-proc.done:
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
}
|
||||
if !claudeGroupStopped(proc.pid) {
|
||||
return inv, nil, errors.Join(ctx.Err(), ErrStageCleanup)
|
||||
}
|
||||
return inv, nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// claudeGroupStopped kills what is left of an exited CLI's process group and
|
||||
// reports whether the group is proven gone.
|
||||
func claudeGroupStopped(pid int) bool {
|
||||
if pid <= 1 {
|
||||
return true // No process of this server's to prove (see exitedClaudeProcess).
|
||||
}
|
||||
if claudeGroupGone(pid) {
|
||||
return true
|
||||
}
|
||||
_ = syscall.Kill(-pid, syscall.SIGKILL)
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for !claudeGroupGone(pid) && time.Now().Before(deadline) {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
return claudeGroupGone(pid)
|
||||
}
|
||||
|
||||
// settle proves the invocation's process group is gone and turns what its
|
||||
// output reported into the invocation's result.
|
||||
func (c *ClaudeStageClient) settle(ctx context.Context, proc *claudeProcess, inv claudeInvocation, waitErr error) (string, error) {
|
||||
// The CLI's exit alone does not prove its shell descendants exited.
|
||||
if !claudeGroupGone(cmd.Process.Pid) {
|
||||
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for !claudeGroupGone(cmd.Process.Pid) && time.Now().Before(deadline) {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
if !claudeGroupGone(cmd.Process.Pid) {
|
||||
return "", errors.Join(waitErr, ErrStageCleanup)
|
||||
}
|
||||
if !claudeGroupStopped(proc.pid) {
|
||||
return "", errors.Join(waitErr, ErrStageCleanup)
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return "", ctx.Err()
|
||||
}
|
||||
for _, denial := range inv.denials {
|
||||
c.noteDenial(denial)
|
||||
}
|
||||
final := inv.final
|
||||
if final != nil {
|
||||
if usageErr := c.observe(final); usageErr != nil {
|
||||
return "", usageErr
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case authFailed:
|
||||
case inv.authFailed:
|
||||
return "", fmt.Errorf("%w: %w", ErrHarnessTransport, errClaudeSignedOut)
|
||||
case refusal || (limited && (final == nil || final.IsError)):
|
||||
if resetsAt > 0 {
|
||||
// A usage window, not an empty account: say when it reopens (a
|
||||
// time only; no provider text is copied).
|
||||
return "", fmt.Errorf("%w: %w; the Claude usage limit resets at %s", ErrHarnessTransport, opencode.ErrProviderQuota, time.Unix(resetsAt, 0).Format("15:04 on 2 Jan"))
|
||||
case inv.refusal || (inv.limited && (final == nil || final.IsError)) || (final != nil && final.IsError && claudeUsageLimitText(final.Result)):
|
||||
if inv.limited || !inv.refusal {
|
||||
// A subscription usage window, not an empty account: say when it
|
||||
// reopens (a time only; no provider text is copied).
|
||||
quota := &QuotaError{Subscription: true}
|
||||
if inv.resetsAt > 0 {
|
||||
quota.ResetsAt = time.Unix(inv.resetsAt, 0)
|
||||
} else if final != nil {
|
||||
if at, ok := claude.UsageLimitResetIn(final.Result, time.Now()); ok {
|
||||
quota.ResetsAt = at
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("%w: %w", ErrHarnessTransport, quota)
|
||||
}
|
||||
return "", fmt.Errorf("%w: %w", ErrHarnessTransport, opencode.ErrProviderQuota)
|
||||
case sessionMismatch || modelMismatch:
|
||||
return "", fmt.Errorf("%w: %w", ErrHarnessTransport, &QuotaError{})
|
||||
case inv.sessionMismatch || inv.modelMismatch:
|
||||
return "", fmt.Errorf("%w: Claude Code did not start the requested session and model", ErrHarnessTransport)
|
||||
case final == nil && proc.adopted:
|
||||
return "", fmt.Errorf("%w: %w", ErrHarnessTransport, errClaudeStoppedUnwatched)
|
||||
case final == nil:
|
||||
if waitErr != nil {
|
||||
return "", fmt.Errorf("%w: Claude Code exited with an error before a result (see the retained stderr log)", ErrHarnessTransport)
|
||||
@@ -536,6 +924,74 @@ func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model,
|
||||
return final.Result, nil
|
||||
}
|
||||
|
||||
// claudeUsageLimitText reports whether a result's text is Claude Code's
|
||||
// usage-limit refusal (the text is only matched, never copied).
|
||||
func claudeUsageLimitText(text string) bool {
|
||||
return claude.IsUsageLimitText(text)
|
||||
}
|
||||
|
||||
// claudeProcessAlive reports whether pid is a live (not zombie) process whose
|
||||
// command line names the session, so a recorded pid the system reused is never
|
||||
// mistaken for the stage's CLI.
|
||||
func claudeProcessAlive(pid int, session string) bool {
|
||||
if pid <= 1 || session == "" {
|
||||
return false
|
||||
}
|
||||
if _, err := os.Stat("/proc/self/stat"); err != nil {
|
||||
return syscall.Kill(pid, 0) == nil // No procfs: liveness only.
|
||||
}
|
||||
stat, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if i := bytes.LastIndexByte(stat, ')'); i < 0 || i+2 >= len(stat) || stat[i+2] == 'Z' || stat[i+2] == 'X' {
|
||||
return false
|
||||
}
|
||||
cmdline, err := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid))
|
||||
return err == nil && bytes.Contains(cmdline, []byte(session))
|
||||
}
|
||||
|
||||
// ClaudeStageReattachable reports whether a Claude Code stage session a
|
||||
// stopped server left owned can be re-adopted: its CLI still runs, or it ended
|
||||
// with a final result while no server was watching (or it was in the outcome
|
||||
// repair follow-up, which follows a complete result). Otherwise the error says
|
||||
// why.
|
||||
func ClaudeStageReattachable(reference, sessionID string) error {
|
||||
owner, err := claudeStageOwnerAt(reference)
|
||||
if err != nil || owner.SessionID != sessionID {
|
||||
return errors.New("its retained evidence is missing or invalid")
|
||||
}
|
||||
if owner.Output == "" {
|
||||
return errors.New("it was started by a server version that ran Claude Code as its own child")
|
||||
}
|
||||
if claudeProcessAlive(owner.PID, sessionID) || owner.Invocation > 0 {
|
||||
return nil
|
||||
}
|
||||
root, err := claudeStageRoot(reference)
|
||||
if err != nil {
|
||||
return errors.New("its retained evidence is missing or invalid")
|
||||
}
|
||||
defer root.Close()
|
||||
f, err := piOpenEvidence(root, owner.Output)
|
||||
if err != nil {
|
||||
return errors.New("its Claude Code output is missing")
|
||||
}
|
||||
defer f.Close()
|
||||
reader := bufio.NewReaderSize(f, 64<<10)
|
||||
for {
|
||||
line, readErr := reader.ReadBytes('\n')
|
||||
var record struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
if json.Unmarshal(line, &record) == nil && record.Type == "result" {
|
||||
return nil
|
||||
}
|
||||
if readErr != nil {
|
||||
return errClaudeStoppedUnwatched
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func claudeGroupGone(pid int) bool {
|
||||
return errors.Is(syscall.Kill(-pid, 0), syscall.ESRCH)
|
||||
}
|
||||
|
||||
@@ -76,9 +76,47 @@ func claudeStageRead(root *os.Root, name string, limit int64) ([]byte, bool, err
|
||||
return data, false, err
|
||||
}
|
||||
|
||||
// claudeStageOwner is the retained owner record of a Claude stage visit's
|
||||
// current CLI invocation. Output names the file the detached CLI writes its
|
||||
// stream-json to; it is empty for a visit an older server ran as its own child
|
||||
// (with piped output), which a restart cannot re-adopt.
|
||||
type claudeStageOwner struct {
|
||||
PID int `json:"pid"`
|
||||
SessionID string `json:"session_id"`
|
||||
PID int `json:"pid"`
|
||||
PGID int `json:"pgid,omitempty"`
|
||||
SessionID string `json:"session_id"`
|
||||
Invocation int `json:"invocation,omitempty"`
|
||||
Output string `json:"output,omitempty"`
|
||||
}
|
||||
|
||||
// writeClaudeStageOwner replaces the owner record atomically, so a server
|
||||
// stopped mid-write never leaves a torn record behind.
|
||||
func writeClaudeStageOwner(reference string, owner claudeStageOwner) error {
|
||||
data, err := json.Marshal(owner)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
temp := filepath.Join(reference, "owner.json.tmp")
|
||||
if err := os.WriteFile(temp, data, 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(temp, filepath.Join(reference, "owner.json"))
|
||||
}
|
||||
|
||||
// claudeStageOwnerAt reads the owner record of a validated evidence directory.
|
||||
func claudeStageOwnerAt(reference string) (claudeStageOwner, error) {
|
||||
root, err := claudeStageRoot(reference)
|
||||
if err != nil {
|
||||
return claudeStageOwner{}, err
|
||||
}
|
||||
defer root.Close()
|
||||
owner, err := claudeStageOwnerOf(root)
|
||||
if err != nil {
|
||||
return owner, err
|
||||
}
|
||||
if owner.Output != "" && owner.Output != claudeOutputName(owner.Invocation) {
|
||||
return owner, fmt.Errorf("invalid retained Claude stage owner")
|
||||
}
|
||||
return owner, nil
|
||||
}
|
||||
|
||||
func claudeStageOwnerOf(root *os.Root) (claudeStageOwner, error) {
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
package stage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// detachClaudeMidInvocation runs Generate until invocation n's CLI has started
|
||||
// working, then stops the "server" (a shutdown-caused cancel). The CLI must be
|
||||
// left running and owned.
|
||||
func detachClaudeMidInvocation(t *testing.T, client *ClaudeStageClient, ctx context.Context, config ModelConfig, n int) claudeStageOwner {
|
||||
t.Helper()
|
||||
run, stop := context.WithCancelCause(ctx)
|
||||
defer stop(nil)
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := client.Generate(run, config, "the task")
|
||||
done <- err
|
||||
}()
|
||||
waitForClaudeOutput(t, n, `"init"`)
|
||||
stop(ErrServerShutdown)
|
||||
if err := <-done; !errors.Is(err, ErrDetached) {
|
||||
t.Fatalf("a server shutdown did not detach the stage: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(client.Reference, "quiescent")); err == nil {
|
||||
t.Fatal("a detached stage was marked quiescent")
|
||||
}
|
||||
owner, err := claudeStageOwnerAt(client.Reference)
|
||||
if err != nil || owner.Invocation != n || owner.SessionID != client.SessionID {
|
||||
t.Fatalf("owner %+v %v", owner, err)
|
||||
}
|
||||
if !claudeProcessAlive(owner.PID, client.SessionID) {
|
||||
t.Fatal("the server shutdown stopped the Claude Code CLI")
|
||||
}
|
||||
if err := ClaudeStageReattachable(client.Reference, client.SessionID); err != nil {
|
||||
t.Fatalf("a running stage is not reattachable: %v", err)
|
||||
}
|
||||
return owner
|
||||
}
|
||||
|
||||
// waitForClaudeOutput waits until the (only) stage evidence directory's
|
||||
// invocation n output contains needle and returns that directory. It reads the
|
||||
// file system, never the client a running Generate is writing.
|
||||
func waitForClaudeOutput(t *testing.T, n int, needle string) string {
|
||||
t.Helper()
|
||||
cache, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for {
|
||||
dirs, _ := filepath.Glob(filepath.Join(cache, "pipelines", claudeStageSessions, "stage-*"))
|
||||
for _, dir := range dirs {
|
||||
if data, err := os.ReadFile(filepath.Join(dir, claudeOutputName(n))); err == nil && strings.Contains(string(data), needle) {
|
||||
return dir
|
||||
}
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("invocation %d never started", n)
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// restartedClaudeClient is the next server process's client for the same visit.
|
||||
func restartedClaudeClient(first *ClaudeStageClient) (*ClaudeStageClient, *[]bool) {
|
||||
active := &[]bool{}
|
||||
return &ClaudeStageClient{Executable: first.Executable, Directory: first.Directory, Tools: first.Tools, Reference: first.Reference, OnOwnership: func(_, _ string, value bool) error {
|
||||
*active = append(*active, value)
|
||||
return nil
|
||||
}}, active
|
||||
}
|
||||
|
||||
func release(t *testing.T, root string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(filepath.Join(root, "release"), nil, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func waitGone(t *testing.T, pid int) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for !claudeGroupGone(pid) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("the CLI did not exit")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClaudeStageSurvivesServerRestart: a server restart mid-stage leaves the
|
||||
// CLI running; the next process re-adopts it, keeps reading its output, waits
|
||||
// for its result and settles the visit, without prompting again.
|
||||
func TestClaudeStageSurvivesServerRestart(t *testing.T) {
|
||||
first, root, firstActive := fakeClaudeClient(t, "slow")
|
||||
owner := detachClaudeMidInvocation(t, first, context.Background(), claudeConfig(nil), 0)
|
||||
if !slices.Equal(*firstActive, []bool{true}) {
|
||||
t.Fatal("the detaching process released ownership", *firstActive)
|
||||
}
|
||||
second, active := restartedClaudeClient(first)
|
||||
budget := NewBudget(10, 1000)
|
||||
ctx, cancel := context.WithTimeout(WithResumeSession(context.Background(), first.SessionID), 10*time.Second)
|
||||
defer cancel()
|
||||
go func() { time.Sleep(200 * time.Millisecond); release(t, root) }()
|
||||
text, err := second.Generate(ctx, claudeConfig(budget), "never sent")
|
||||
if err != nil || text != "done" {
|
||||
t.Fatal(text, err)
|
||||
}
|
||||
if calls := fakeClaudeArgs(t, root); len(calls) != 1 {
|
||||
t.Fatalf("the restarted server prompted again: %v", calls)
|
||||
}
|
||||
if prompt, _ := os.ReadFile(filepath.Join(root, "prompt")); string(prompt) != "the task" {
|
||||
t.Fatalf("prompt %q", prompt)
|
||||
}
|
||||
if !slices.Equal(*active, []bool{true, false}) || !second.WorkStarted || second.SessionID != first.SessionID {
|
||||
t.Fatal("ownership", *active, second.WorkStarted)
|
||||
}
|
||||
if used := budget.Snapshot(); used.UsedUSD != 0.25 || used.UsedTokens != 17 {
|
||||
t.Fatalf("usage %+v", used)
|
||||
}
|
||||
if !claudeGroupGone(owner.PID) {
|
||||
t.Fatal("the adopted CLI's group is still running")
|
||||
}
|
||||
// The evidence lists each record once and the export reads it.
|
||||
data, err := ClaudeStageEvidence(first.Reference)
|
||||
if err != nil || strings.Count(data, `"working"`) != 1 || strings.Count(data, `"type":"result"`) != 1 {
|
||||
t.Fatalf("evidence %q %v", data, err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(first.Reference, claudeOutputName(0))); !os.IsNotExist(err) {
|
||||
t.Fatal("the raw CLI output outlived the settled visit")
|
||||
}
|
||||
session, err := exportClaudeStageSession(ctx, SessionExportRequest{Backend: ClaudeBackend, SessionID: first.SessionID, Reference: first.Reference})
|
||||
if err != nil || len(session.Messages) == 0 {
|
||||
t.Fatalf("export %+v %v", session, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClaudeStageFinishedWhileServerWasDown: the CLI completed while no server
|
||||
// ran; the next process reads the result it left.
|
||||
func TestClaudeStageFinishedWhileServerWasDown(t *testing.T) {
|
||||
first, root, _ := fakeClaudeClient(t, "slow")
|
||||
owner := detachClaudeMidInvocation(t, first, context.Background(), claudeConfig(nil), 0)
|
||||
release(t, root)
|
||||
waitGone(t, owner.PID)
|
||||
if err := ClaudeStageReattachable(first.Reference, first.SessionID); err != nil {
|
||||
t.Fatalf("a completed stage is not reattachable: %v", err)
|
||||
}
|
||||
second, active := restartedClaudeClient(first)
|
||||
text, err := second.Generate(WithResumeSession(context.Background(), first.SessionID), claudeConfig(nil), "never sent")
|
||||
if err != nil || text != "done" || !slices.Equal(*active, []bool{true, false}) {
|
||||
t.Fatal(text, err, *active)
|
||||
}
|
||||
if calls := fakeClaudeArgs(t, root); len(calls) != 1 {
|
||||
t.Fatalf("the restarted server prompted again: %v", calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClaudeStageDiedWithoutResultWhileServerWasDown: a CLI that ended
|
||||
// without a result while no server watched is never prompted again; recovery
|
||||
// says why.
|
||||
func TestClaudeStageDiedWithoutResultWhileServerWasDown(t *testing.T) {
|
||||
first, root, _ := fakeClaudeClient(t, "slow")
|
||||
owner := detachClaudeMidInvocation(t, first, context.Background(), claudeConfig(nil), 0)
|
||||
_ = syscall.Kill(-owner.PID, syscall.SIGKILL)
|
||||
waitGone(t, owner.PID)
|
||||
err := ClaudeStageReattachable(first.Reference, first.SessionID)
|
||||
if !errors.Is(err, errClaudeStoppedUnwatched) {
|
||||
t.Fatalf("a dead stage without a result was reattachable: %v", err)
|
||||
}
|
||||
// Adopting anyway (a death between the plan and the adoption) fails
|
||||
// closed with the same diagnostic and settles ownership.
|
||||
second, active := restartedClaudeClient(first)
|
||||
_, err = second.Generate(WithResumeSession(context.Background(), first.SessionID), claudeConfig(nil), "never sent")
|
||||
if !errors.Is(err, ErrHarnessTransport) || !errors.Is(err, errClaudeStoppedUnwatched) || !slices.Equal(*active, []bool{true, false}) {
|
||||
t.Fatal(err, *active)
|
||||
}
|
||||
if calls := fakeClaudeArgs(t, root); len(calls) != 1 {
|
||||
t.Fatalf("a lost prompt was sent again: %v", calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClaudeStageRestartDuringOutcomeRepair: a restart during the outcome
|
||||
// repair follow-up re-adopts that follow-up; the prompt's report is read back
|
||||
// from its retained output and merged with the reply, and both invocations'
|
||||
// usage counts.
|
||||
func TestClaudeStageRestartDuringOutcomeRepair(t *testing.T) {
|
||||
first, root, _ := fakeClaudeClient(t, "slowrepair")
|
||||
repair := withOutputRepair(context.Background(), []string{"error", "success"})
|
||||
detachClaudeMidInvocation(t, first, repair, claudeConfig(nil), 1)
|
||||
second, active := restartedClaudeClient(first)
|
||||
budget := NewBudget(0, 1000)
|
||||
go func() { time.Sleep(200 * time.Millisecond); release(t, root) }()
|
||||
text, err := second.Generate(WithResumeSession(repair, first.SessionID), claudeConfig(budget), "never sent")
|
||||
if err != nil || !strings.HasPrefix(text, "# outcome\nsuccess\n") || !strings.Contains(text, "Report kept.") {
|
||||
t.Fatalf("%q %v", text, err)
|
||||
}
|
||||
if calls := fakeClaudeArgs(t, root); len(calls) != 2 {
|
||||
t.Fatalf("invocations %v", calls)
|
||||
}
|
||||
if budget.Snapshot().UsedTokens != 34 || !slices.Equal(*active, []bool{true, false}) {
|
||||
t.Fatalf("usage %+v ownership %v", budget.Snapshot(), *active)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClaudeStageLostRepairFollowUpIsSentAgain: the follow-up's CLI died
|
||||
// without a reply while the server was down; it only asks for the outcome,
|
||||
// so the next process asks again instead of failing the visit.
|
||||
func TestClaudeStageLostRepairFollowUpIsSentAgain(t *testing.T) {
|
||||
first, root, _ := fakeClaudeClient(t, "slowrepair")
|
||||
repair := withOutputRepair(context.Background(), []string{"error", "success"})
|
||||
owner := detachClaudeMidInvocation(t, first, repair, claudeConfig(nil), 1)
|
||||
_ = syscall.Kill(-owner.PID, syscall.SIGKILL)
|
||||
waitGone(t, owner.PID)
|
||||
if err := ClaudeStageReattachable(first.Reference, first.SessionID); err != nil {
|
||||
t.Fatalf("a visit with a complete prompt result is not reattachable: %v", err)
|
||||
}
|
||||
release(t, root)
|
||||
second, _ := restartedClaudeClient(first)
|
||||
text, err := second.Generate(WithResumeSession(repair, first.SessionID), claudeConfig(nil), "never sent")
|
||||
if err != nil || !strings.HasPrefix(text, "# outcome\nsuccess\n") {
|
||||
t.Fatalf("%q %v", text, err)
|
||||
}
|
||||
calls := fakeClaudeArgs(t, root)
|
||||
if len(calls) != 3 || !slices.Contains(calls[2], "--resume") {
|
||||
t.Fatalf("invocations %v", calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClaudeStageOperatorCancelStillStopsTheCLI: only a server shutdown
|
||||
// detaches; an ordinary cancel stops the detached process group.
|
||||
func TestClaudeStageOperatorCancelStillStopsTheCLI(t *testing.T) {
|
||||
client, _, active := fakeClaudeClient(t, "slow")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := client.Generate(ctx, claudeConfig(nil), "task")
|
||||
done <- err
|
||||
}()
|
||||
owner, _ := claudeStageOwnerAt(waitForClaudeOutput(t, 0, "working"))
|
||||
cancel()
|
||||
if err := <-done; !errors.Is(err, context.Canceled) || errors.Is(err, ErrDetached) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !claudeGroupGone(owner.PID) || !slices.Equal(*active, []bool{true, false}) {
|
||||
t.Fatal("cancel left the CLI running", *active)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaudeStageLegacyOwnerIsNotReattachable(t *testing.T) {
|
||||
client, _, _ := fakeClaudeClient(t, "success")
|
||||
if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(client.Reference, "owner.json"), []byte(`{"pid":99999999,"session_id":"`+client.SessionID+`"}`), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ClaudeStageReattachable(client.Reference, client.SessionID); err == nil || !strings.Contains(err.Error(), "server version") {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,24 @@ case "$FAKE_CLAUDE_CASE" in
|
||||
if [ "$resumed" = 1 ]; then text='# outcome\nsuccess\n'; else text='Report kept.'; fi
|
||||
printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"result":"'"$text"'","session_id":"'"$session"'",'"$usage"'}'
|
||||
;;
|
||||
slow)
|
||||
# Works until the test releases it (a server restart happens meanwhile).
|
||||
init "$session" "$model"
|
||||
echo '{"type":"assistant","session_id":"'"$session"'","message":{"role":"assistant","content":[{"type":"text","text":"working"}]}}'
|
||||
while [ ! -e "$FAKE_CLAUDE_OUT/release" ]; do sleep 0.02; done
|
||||
echo '{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"'"$session"'",'"$usage"'}'
|
||||
;;
|
||||
slowrepair)
|
||||
# The prompt's report lacks an outcome; the follow-up waits for release.
|
||||
init "$session" "$model"
|
||||
if [ "$resumed" = 1 ]; then
|
||||
while [ ! -e "$FAKE_CLAUDE_OUT/release" ]; do sleep 0.02; done
|
||||
text='# outcome\nsuccess\n'
|
||||
else
|
||||
text='Report kept.'
|
||||
fi
|
||||
printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"result":"'"$text"'","session_id":"'"$session"'",'"$usage"'}'
|
||||
;;
|
||||
nousage)
|
||||
init "$session" "$model"
|
||||
echo '{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"'"$session"'"}'
|
||||
@@ -74,6 +92,18 @@ case "$FAKE_CLAUDE_CASE" in
|
||||
echo '{"type":"result","subtype":"success","is_error":true,"result":"PROVIDER-BODY-SECRET","session_id":"'"$session"'",'"$usage"'}'
|
||||
exit 1
|
||||
;;
|
||||
ratelimit)
|
||||
init "$session" "$model"
|
||||
echo '{"type":"assistant","session_id":"'"$session"'","error":"rate_limit","message":{"role":"assistant","error":"rate_limit","content":[{"type":"text","text":"Claude AI usage limit reached|1794409200"}]}}'
|
||||
echo '{"type":"result","subtype":"success","is_error":true,"result":"Claude AI usage limit reached|1794409200","session_id":"'"$session"'",'"$usage"'}'
|
||||
exit 1
|
||||
;;
|
||||
denied)
|
||||
init "$session" "$model"
|
||||
echo '{"type":"assistant","session_id":"'"$session"'","message":{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Edit","input":{"file_path":"/etc/hosts"}}]}}'
|
||||
echo '{"type":"user","session_id":"'"$session"'","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","is_error":true,"content":"Claude requested permissions to write to /etc/hosts, but you have not granted it yet."}]}}'
|
||||
printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"result":"# outcome\nblocked\n","session_id":"'"$session"'","permission_denials":[{"tool_name":"Bash","tool_use_id":"t2","tool_input":{"command":"git push origin main"}}],'"$usage"'}'
|
||||
;;
|
||||
auth)
|
||||
init "$session" "$model"
|
||||
echo '{"type":"assistant","session_id":"'"$session"'","error":"authentication_failed","message":{"role":"assistant","content":[{"type":"text","text":"PROVIDER-BODY-SECRET"}]}}'
|
||||
@@ -228,6 +258,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 +352,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")
|
||||
@@ -290,7 +387,15 @@ func TestClaudeStageFailuresAreFixedText(t *testing.T) {
|
||||
"quota": func(err error) bool { return errors.Is(err, opencode.ErrProviderQuota) },
|
||||
// A usage window names when it reopens.
|
||||
"limited": func(err error) bool {
|
||||
return errors.Is(err, opencode.ErrProviderQuota) && strings.Contains(err.Error(), "usage limit resets at")
|
||||
at, ok := QuotaResetsAt(err)
|
||||
return errors.Is(err, opencode.ErrProviderQuota) && SubscriptionQuota(err) && ok && at.Unix() == 1794409200 &&
|
||||
strings.Contains(err.Error(), "resets at") && !strings.Contains(err.Error(), "top up")
|
||||
},
|
||||
// A subscription refusal named only by the assistant's error and
|
||||
// the CLI's own text still parks with the reset the text names.
|
||||
"ratelimit": func(err error) bool {
|
||||
at, ok := QuotaResetsAt(err)
|
||||
return errors.Is(err, opencode.ErrProviderQuota) && SubscriptionQuota(err) && ok && at.Unix() == 1794409200 && !strings.Contains(err.Error(), "top up")
|
||||
},
|
||||
"auth": func(err error) bool { return errors.Is(err, errClaudeSignedOut) },
|
||||
"maxturns": func(err error) bool { return strings.Contains(err.Error(), "(error_max_turns)") },
|
||||
@@ -326,7 +431,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 +445,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 +504,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),
|
||||
} {
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
package stage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// QuotaError is a provider usage-limit refusal. It matches
|
||||
// opencode.ErrProviderQuota with errors.Is. ResetsAt is when the limit resets
|
||||
// (zero when the refusal did not say). A subscription window (Claude's 5-hour
|
||||
// or weekly limit) is not an empty account, so its text never asks the
|
||||
// operator to top anything up.
|
||||
type QuotaError struct {
|
||||
ResetsAt time.Time
|
||||
Subscription bool
|
||||
}
|
||||
|
||||
func (e *QuotaError) Error() string {
|
||||
if !e.Subscription {
|
||||
return opencode.ErrProviderQuota.Error()
|
||||
}
|
||||
if e.ResetsAt.IsZero() {
|
||||
return "the Claude usage limit was reached; the run continues when it resets"
|
||||
}
|
||||
return "the Claude usage limit was reached; it resets at " + e.ResetsAt.Local().Format("15:04 on 2 Jan")
|
||||
}
|
||||
|
||||
func (e *QuotaError) Unwrap() error { return opencode.ErrProviderQuota }
|
||||
|
||||
// QuotaResetsAt returns the reset time a usage-limit error carries.
|
||||
func QuotaResetsAt(err error) (time.Time, bool) {
|
||||
var quota *QuotaError
|
||||
if errors.As(err, "a) && !quota.ResetsAt.IsZero() {
|
||||
return quota.ResetsAt, true
|
||||
}
|
||||
return time.Time{}, false
|
||||
}
|
||||
|
||||
// SubscriptionQuota reports whether err is a subscription usage window (one
|
||||
// that resets on its own), as opposed to an exhausted paid balance.
|
||||
func SubscriptionQuota(err error) bool {
|
||||
var quota *QuotaError
|
||||
return errors.As(err, "a) && quota.Subscription
|
||||
}
|
||||
|
||||
// ErrPermissionDenied is a stage whose declared tool use was refused by the
|
||||
// harness's permission rules and that then gave up (answered blocked or
|
||||
// error) instead of finishing its work.
|
||||
var ErrPermissionDenied = errors.New("tool permission denied")
|
||||
|
||||
// PermissionDeniedError names the refused tool uses (bounded).
|
||||
type PermissionDeniedError struct{ Denials []string }
|
||||
|
||||
func (e *PermissionDeniedError) Error() string {
|
||||
return fmt.Sprintf("%s: %s; widen the stage's tools or run write paths, or change the task", ErrPermissionDenied, strings.Join(e.Denials, ", "))
|
||||
}
|
||||
|
||||
func (e *PermissionDeniedError) Unwrap() error { return ErrPermissionDenied }
|
||||
|
||||
// permissionDenier is a client that observed tool permission denials.
|
||||
type permissionDenier interface{ PermissionDenials() []string }
|
||||
|
||||
// ErrRunBudgetExceeded is the whole-run USD cap; it also matches
|
||||
// ErrBudgetExceeded.
|
||||
var ErrRunBudgetExceeded = errors.New("run budget exceeded")
|
||||
|
||||
// Harness failure kinds (HarnessFailureKind).
|
||||
const (
|
||||
HarnessTransient = "transient"
|
||||
HarnessDeterministic = "deterministic"
|
||||
// HarnessRepeatable is a harness failure that is deterministic when it
|
||||
// repeats on the next visit of the same stage (an empty readback).
|
||||
HarnessRepeatable = "repeatable"
|
||||
)
|
||||
|
||||
// HarnessFailureKind classifies a stage failure for the runner's error-loop
|
||||
// policy: transient failures (network, 5xx, overloaded, timeouts) are worth
|
||||
// another visit after a backoff; deterministic ones (authentication,
|
||||
// invalid arguments, a configuration the harness refuses) fail the same way
|
||||
// every time. "" means the error is not a harness failure.
|
||||
func HarnessFailureKind(err error) string {
|
||||
if err == nil || errors.Is(err, opencode.ErrProviderQuota) || errors.Is(err, ErrBudgetExceeded) || errors.Is(err, context.Canceled) {
|
||||
return ""
|
||||
}
|
||||
if errors.Is(err, ErrPermissionDenied) || errors.Is(err, errClaudeSignedOut) || errors.Is(err, errClaudeMissing) {
|
||||
return HarnessDeterministic
|
||||
}
|
||||
text := strings.ToLower(err.Error())
|
||||
for _, marker := range []string{"authentication", "unauthorized", "invalid api key", "invalid argument", "invalid_request", "unknown option", "unknown model", "model not found", "not supported", "cannot enforce", "needs provider", "did not start the requested session and model"} {
|
||||
if strings.Contains(text, marker) {
|
||||
return HarnessDeterministic
|
||||
}
|
||||
}
|
||||
if strings.Contains(text, "readback contained no assistant message") {
|
||||
return HarnessRepeatable
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, ErrHarnessUnreachable) {
|
||||
return HarnessTransient
|
||||
}
|
||||
for _, marker := range []string{"timeout", "timed out", "connection refused", "connection reset", "broken pipe", "eof", "no such host", "network", "overloaded", "529", "502", "503", "504", "500 internal", "temporarily", "try again"} {
|
||||
if strings.Contains(text, marker) {
|
||||
return HarnessTransient
|
||||
}
|
||||
}
|
||||
if harnessTransportFailure(err) {
|
||||
return HarnessTransient
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// FailureClassOf maps a stage error to the run failure class it causes.
|
||||
func FailureClassOf(err error) string {
|
||||
var deadline *stageDeadlineError
|
||||
switch {
|
||||
case err == nil:
|
||||
return ""
|
||||
case errors.Is(err, opencode.ErrProviderQuota):
|
||||
return protocol.FailureQuota
|
||||
case errors.Is(err, ErrBudgetExceeded):
|
||||
return protocol.FailureBudget
|
||||
case errors.Is(err, ErrPermissionDenied):
|
||||
return protocol.FailurePermissionDenied
|
||||
case errors.Is(err, context.Canceled):
|
||||
return protocol.FailureCanceled
|
||||
case errors.Is(err, errClaudeSignedOut), errors.Is(err, errClaudeMissing), errors.Is(err, ErrHarnessUnreachable):
|
||||
return protocol.FailureEnvironment
|
||||
case errors.As(err, &deadline), errors.Is(err, context.DeadlineExceeded):
|
||||
return protocol.FailureTimeout
|
||||
case harnessTransportFailure(err), errors.Is(err, ErrStageCleanup), errors.Is(err, ErrBudgetAccounting):
|
||||
return protocol.FailureHarnessError
|
||||
}
|
||||
return protocol.FailureOther
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package stage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func TestClaudeStagePermissionDenialFailsABlockedVisit(t *testing.T) {
|
||||
client, _, _ := fakeClaudeClient(t, "denied")
|
||||
def := modelDefinition()
|
||||
def.Configs = map[string]string{"harness": ClaudeBackend, "provider": ClaudeProvider, "model": "claude-haiku-5-5", "retries": "0"}
|
||||
def.Blocks["configs"] = "harness=claude\nprovider=anthropic\nmodel=claude-haiku-5-5\nretries=0"
|
||||
def.Edges = map[string]string{"success": protocol.SuccessEnd, "blocked": protocol.FailureEnd, "error": protocol.FailureEnd}
|
||||
_, err := (ModelStage{Client: client}).Run(context.Background(), def, nil)
|
||||
if !errors.Is(err, ErrPermissionDenied) || FailureClassOf(err) != protocol.FailurePermissionDenied {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, want := range []string{"Edit(/etc/hosts)", "Bash(git push origin main)"} {
|
||||
if !strings.Contains(err.Error(), want) {
|
||||
t.Fatalf("diagnostic %q does not name %s", err, want)
|
||||
}
|
||||
}
|
||||
if HarnessFailureKind(err) != HarnessDeterministic {
|
||||
t.Fatal("a permission denial repeats on the next visit")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaErrorWording(t *testing.T) {
|
||||
reset := time.Date(2026, 12, 3, 9, 0, 0, 0, time.UTC)
|
||||
subscription := fmt.Errorf("%w: %w", ErrHarnessTransport, &QuotaError{Subscription: true, ResetsAt: reset})
|
||||
if !errors.Is(subscription, opencode.ErrProviderQuota) || strings.Contains(subscription.Error(), "top up") {
|
||||
t.Fatal(subscription)
|
||||
}
|
||||
if at, ok := QuotaResetsAt(subscription); !ok || !at.Equal(reset) {
|
||||
t.Fatal(at, ok)
|
||||
}
|
||||
balance := &QuotaError{}
|
||||
if !strings.Contains(balance.Error(), "top up") || SubscriptionQuota(balance) {
|
||||
t.Fatal("an exhausted paid balance keeps the top-up advice")
|
||||
}
|
||||
if FailureClassOf(subscription) != protocol.FailureQuota || HarnessFailureKind(subscription) != "" {
|
||||
t.Fatal("quota is its own class, never a harness retry")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHarnessFailureKinds(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
err error
|
||||
kind string
|
||||
}{
|
||||
{fmt.Errorf("%w: connection refused", ErrHarnessUnreachable), HarnessTransient},
|
||||
{&openCodeError{status: 503}, HarnessTransient},
|
||||
{fmt.Errorf("%w: the provider is overloaded", ErrHarnessTransport), HarnessTransient},
|
||||
{fmt.Errorf("x: %w", context.DeadlineExceeded), HarnessTransient},
|
||||
{fmt.Errorf("%w: final assistant readback contained no assistant message", ErrHarnessTransport), HarnessRepeatable},
|
||||
{fmt.Errorf("%w: %w", ErrHarnessTransport, errClaudeSignedOut), HarnessDeterministic},
|
||||
{fmt.Errorf("%w: invalid argument --tools", ErrHarnessTransport), HarnessDeterministic},
|
||||
{errors.New("plain stage error"), ""},
|
||||
{fmt.Errorf("%w: USD 2 / 1", ErrBudgetExceeded), ""},
|
||||
} {
|
||||
if got := HarnessFailureKind(tc.err); got != tc.kind {
|
||||
t.Errorf("%v: kind %q, want %q", tc.err, got, tc.kind)
|
||||
}
|
||||
}
|
||||
for err, class := range map[error]string{
|
||||
fmt.Errorf("%w: %w", ErrBudgetExceeded, ErrRunBudgetExceeded): protocol.FailureBudget,
|
||||
&stageDeadlineError{timeout: time.Second}: protocol.FailureTimeout,
|
||||
fmt.Errorf("%w: x", ErrHarnessTransport): protocol.FailureHarnessError,
|
||||
fmt.Errorf("%w: x", ErrHarnessUnreachable): protocol.FailureEnvironment,
|
||||
context.Canceled: protocol.FailureCanceled,
|
||||
errors.New("anything else"): protocol.FailureOther,
|
||||
} {
|
||||
if got := FailureClassOf(err); got != class {
|
||||
t.Errorf("%v: class %q, want %q", err, got, class)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 with shell but no 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")
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -90,6 +90,13 @@ func (m ModelStage) Run(ctx context.Context, def Definition, input Values) (Resu
|
||||
}
|
||||
cancel()
|
||||
if resultErr == nil {
|
||||
// A stage that gave up after its tool use was refused failed on
|
||||
// the permission rules, not on the task: say which use.
|
||||
if denier, ok := client.(permissionDenier); ok && (result.Outcome == "blocked" || result.Outcome == "error") {
|
||||
if denials := denier.PermissionDenials(); len(denials) > 0 {
|
||||
return result, wrapModelStageFailure(def.Key, &PermissionDeniedError{Denials: denials})
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
// A malformed final result mutates nothing on an explicit read-only
|
||||
|
||||
@@ -249,3 +249,20 @@ func writeOperatorSkillPlugins(dir string, groups []OperatorSkillGroup) ([]strin
|
||||
}
|
||||
return roots, nil
|
||||
}
|
||||
|
||||
// existingOperatorSkillPlugins lists the skills-only plugin roots an earlier
|
||||
// process generated in dir (see writeOperatorSkillPlugins), for a re-adopted
|
||||
// visit whose follow-up must offer the same skills.
|
||||
func existingOperatorSkillPlugins(dir string) []string {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var roots []string
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() {
|
||||
roots = append(roots, filepath.Join(dir, entry.Name()))
|
||||
}
|
||||
}
|
||||
return roots
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user