Merge branch 'worktree-agent-add3194df2bcbd3c5'

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 14:21:07 +00:00
48 changed files with 2684 additions and 131 deletions
+1 -1
View File
@@ -126,7 +126,7 @@ func TestChatTurnDiffMarksBoundedPatchesTruncated(t *testing.T) {
dir := gitRepo(t, map[string]string{"a.txt": "x\n"})
h := turnDiffHub(t, dir)
h.startRoomTurnDiff("ses_1")
writeTurnFile(t, dir, "big.txt", strings.Repeat("line\n", 6000))
writeTurnFile(t, dir, "big.txt", strings.Repeat("line\n", 21000))
endDiffTurn(h, "ses_1")
turns := recordedTurns(t, h, "ses_1")
if len(turns) != 1 || !turns[0].Truncated || turns[0].Files != 1 || turns[0].Status != "partial" {
+146
View File
@@ -0,0 +1,146 @@
package server
import (
"context"
"errors"
"fmt"
"os"
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
// errDeliveryChecksFailed marks a delivery check stage whose commands ran and
// failed on the candidate: that is the stage's fail outcome, not an error.
var errDeliveryChecksFailed = errors.New("delivery checks failed")
// runCheckStage executes a check stage. Without delivery its commands run in
// place in the run workspace. With delivery=true it is the landing gate: the
// server commits the run's leftovers, merges a moved main, runs the commands
// in a fresh candidate worktree of the commit and fast-forwards main only when
// every command passes. A failing command is the fail outcome (main is not
// touched); a gate failure (dirty checkout, conflict, refused fast-forward) is
// an error.
func (r *runner) runCheckStage(ctx context.Context, def stage.Definition, workspace string, delivery bool, landing stage.LandingAccess, runID int64) (stage.Result, error) {
spec, err := stage.CheckStageSpec(def)
if err != nil {
return stage.Result{}, err
}
if !delivery {
def.Workspace = workspace
return stage.CheckStage{}.Run(ctx, def, nil)
}
ctx, cancel := context.WithTimeout(ctx, spec.Timeout)
defer cancel()
var report stage.CheckReport
note, err := verifyDeliveryWith(ctx, workspace, landing, r.deliveryCommitMessage(runID), func(ctx context.Context, candidate string) error {
report = stage.RunCheckCommands(ctx, candidate, spec)
if report.Failed() {
return errDeliveryChecksFailed
}
return nil
})
if err != nil && !errors.Is(err, errDeliveryChecksFailed) {
return stage.Result{}, err
}
result := stage.CheckResult(def.Key, spec, report)
markdown, _ := result.Output["markdown"].(string)
gate := "Delivery gate: the checks ran on a fresh worktree of the committed item; main was not changed."
if err == nil {
gate = "Delivery gate: the checks passed on a fresh worktree of the committed item and main was fast-forwarded to it."
}
if note != "" {
gate += " " + strings.TrimPrefix(note, "delivery gate: ") + "."
}
result.Output["markdown"] = strings.Replace(markdown, "\n## Commands\n", "\n"+gate+"\n\n## Commands\n", 1)
return result, nil
}
// checkVerdict is the check stage's one-line verdict: its own summary, never
// a model's paraphrase of the command output.
func checkVerdict(output stage.Values) *protocol.StageVerdict {
summary, _ := output["summary"].(string)
if strings.TrimSpace(summary) == "" {
return nil
}
return &protocol.StageVerdict{Reason: summary, ReasonSource: protocol.VerdictReasonFallback}
}
// readOnlyViolation reports the files a stage with shell but without edit
// left changed in the run directory: its shell is for reading, testing and
// committing, not for writing. A stage without shell cannot write at all (a
// change during it is not its own), and a stage with edit may write. Paths
// under the stage's artifacts directory, the run's shared public directory and
// a harness state directory that lives inside the workspace (for example
// CLAUDE_CONFIG_DIR) are the harness's or the run's own and are not counted.
// It returns "" when the stage may change files or none changed.
func readOnlyViolation(def stage.Definition, tools []string, explicitTools bool, changes *protocol.StageFileChanges, workspace string, ignored []string) string {
if stage.EffectiveType(def.Type) != stage.ModelType || !explicitTools || def.Configs["allow_workspace_changes"] == "true" || changes == nil {
return ""
}
shell := false
for _, tool := range tools {
if tool == "edit" {
return ""
}
shell = shell || tool == "shell"
}
if !shell {
return ""
}
var prefixes []string
for _, dir := range ignored {
if rel, ok := workspaceRelative(workspace, dir); ok {
prefixes = append(prefixes, rel+"/")
}
}
var changed []string
for _, file := range changes.Files {
skip := false
for _, prefix := range prefixes {
if prefix == "./" || strings.HasPrefix(file.Path+"/", prefix) {
skip = true
break
}
}
if !skip {
changed = append(changed, file.Kind+" "+file.Path)
}
}
if len(changed) == 0 && changes.Omitted == 0 {
return ""
}
listed := changed
if len(listed) > 20 {
listed = append(append([]string(nil), listed[:20]...), fmt.Sprintf("and %d more", len(changed)-20))
}
if changes.Omitted > 0 {
listed = append(listed, fmt.Sprintf("%d more omitted from the capture", changes.Omitted))
}
return fmt.Sprintf("permission denied: stage %s has no edit tool but changed the workspace (%s); the visit fails. If this stage is meant to change files, add edit to its tools or set allow_workspace_changes=true", def.Key, strings.Join(listed, ", "))
}
// workspaceEnv is the environment a command in workspace runs with: the run's
// directory environment when one applies, else the server's.
func workspaceEnv(ctx context.Context, workspace string) []string {
if env := workenv.CommandEnv(ctx, workspace); env != nil {
return env
}
return os.Environ()
}
// workspaceRelative returns dir relative to workspace when dir is inside it.
func workspaceRelative(workspace, dir string) (string, bool) {
workspace = strings.TrimSuffix(workspace, "/")
dir = strings.TrimSuffix(dir, "/")
if workspace == "" || dir == "" {
return "", false
}
if dir == workspace {
return ".", true
}
rel, ok := strings.CutPrefix(dir, workspace+"/")
return rel, ok && rel != ""
}
+206
View File
@@ -0,0 +1,206 @@
package server
import (
"context"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
func checkModelStage(key, tools, edges, configs string) string {
return "# stage " + key + "\n\n```prompt\nDo the work.\n```\n\n```tools\n" + tools + "\n```\n\n```edges\n" + edges + "\n```\n\n```configs\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n" + configs + "\n```\n\n"
}
func checkTypeStage(key, commands, edges, configs string) string {
return "# stage " + key + "\n\n```limits\n{\"max_visits\":3}\n```\n\n```configs\ntype=check\n" + configs + "\n```\n\n```commands\n" + commands + "\n```\n\n```edges\n" + edges + "\n```\n\n"
}
func startSource(t *testing.T, ctx context.Context, source, workspace string, execute func(context.Context, stage.Definition, stage.Values) (stage.Result, error)) (*protocol.RunDetail, *pipeline.Store) {
t.Helper()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "runner.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { store.Close() })
if _, err := store.Submit(ctx, "check", source); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
r.execute = execute
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: t.Name(), Workspace: workspace, Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, err := store.GetRun(ctx, run.ID)
if err != nil {
t.Fatal(err)
}
return detail, store
}
// A failing check sends the run back to the implementer with the failing
// output in its input; the reviewer only runs once the tree is green.
func TestCheckStageRoutesFailureOutputBackToTheImplementer(t *testing.T) {
ctx := context.Background()
workspace := t.TempDir()
source := checkModelStage("implement", "read\nedit\nshell", "success -> verify\nerror -> #failure", "") +
checkTypeStage("verify", "echo checking\ntest -f fixed || { echo 'FAIL: fixed is missing' >&2; exit 4; }", "pass -> review\nfail -> implement", "") +
checkModelStage("review", "read\nglob\ngrep", "success -> #success\nerror -> #failure", "")
var visits atomic.Int32
var secondInput string
detail, _ := startSource(t, ctx, source, workspace, func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
if def.Key == "implement" {
if visits.Add(1) == 2 {
data, _ := os.ReadFile(def.Turn.Input)
secondInput = string(data)
if err := os.WriteFile(filepath.Join(workspace, "fixed"), []byte("yes\n"), 0o600); err != nil {
return stage.Result{}, err
}
}
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "done"}}, nil
})
if detail.Status != "succeeded" {
t.Fatalf("run %s: %s %+v", detail.Status, detail.Diagnostic, detail.Steps)
}
var stages []string
for _, step := range detail.Steps {
stages = append(stages, step.Stage+":"+step.Outcome)
}
if got := strings.Join(stages, " "); got != "implement:success verify:fail implement:success verify:pass review:success" {
t.Fatal(got)
}
for _, want := range []string{"1 of 2 checks failed", "exit code 4", "FAIL: fixed is missing"} {
if !strings.Contains(secondInput, want) {
t.Fatalf("implementer input lacks %q:\n%s", want, secondInput)
}
}
failed := detail.Steps[1]
if failed.Verdict == nil || !strings.HasPrefix(failed.Verdict.Reason, "1 of 2 checks failed") {
t.Fatalf("verdict %+v", failed.Verdict)
}
checks, _ := failed.Output["checks"].([]any)
if len(checks) != 2 || failed.Provider != "" || failed.SessionID != "" {
t.Fatalf("check step %+v", failed)
}
}
// A delivery check stage is the landing gate: the run's uncommitted work is
// committed, the commands run on a fresh candidate and main fast-forwards;
// a failing command is the fail outcome and leaves main alone.
func TestDeliveryCheckStageLandsOnlyAGreenCandidate(t *testing.T) {
for _, test := range []struct {
name, command, status string
landed bool
}{
{"pass", "test -f work", "succeeded", true},
{"fail", "test -f absent", "failed", false},
} {
t.Run(test.name, func(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
main := filepath.Join(root, "main")
runGit(t, root, "init", "-b", "main", main)
runGit(t, main, "config", "user.email", "test@example.invalid")
runGit(t, main, "config", "user.name", "test")
if err := os.WriteFile(filepath.Join(main, "README"), []byte("base\n"), 0o600); err != nil {
t.Fatal(err)
}
runGit(t, main, "add", "README")
runGit(t, main, "commit", "-m", "base")
item := filepath.Join(root, "item")
runGit(t, main, "worktree", "add", "-b", "item", item)
if err := os.WriteFile(filepath.Join(item, "work"), []byte("change\n"), 0o600); err != nil {
t.Fatal(err)
}
runGit(t, item, "add", "work")
runGit(t, item, "commit", "-m", "work")
before := runGitOutput(t, main, "rev-parse", "HEAD")
source := checkTypeStage("land", test.command, "pass -> #success\nfail -> #failure", "delivery=true")
detail, _ := startSource(t, ctx, source, item, nil)
if detail.Status != test.status || len(detail.Steps) != 1 {
t.Fatalf("run %s %q %+v", detail.Status, detail.Diagnostic, detail.Steps)
}
step := detail.Steps[0]
markdown, _ := step.Output["markdown"].(string)
if !strings.Contains(markdown, "Delivery gate") || step.Output["delivery"] != true {
t.Fatalf("gate evidence missing: %q", markdown)
}
landed := runGitOutput(t, main, "rev-parse", "HEAD") == runGitOutput(t, item, "rev-parse", "HEAD")
if landed != test.landed || (!test.landed && runGitOutput(t, main, "rev-parse", "HEAD") != before) {
t.Fatalf("landed = %v, want %v", landed, test.landed)
}
})
}
}
// A stage without edit that changes the workspace fails its visit and names
// the files; allow_workspace_changes=true opts a stage out.
func TestReadOnlyStageThatChangesFilesFails(t *testing.T) {
ctx := context.Background()
for _, test := range []struct {
name, configs, status string
}{
{"enforced", "", "failed"},
{"allowed", "allow_workspace_changes=true", "succeeded"},
} {
t.Run(test.name, func(t *testing.T) {
workspace := t.TempDir()
if err := os.WriteFile(filepath.Join(workspace, "main.go"), []byte("package main\n"), 0o600); err != nil {
t.Fatal(err)
}
source := checkModelStage("review", "read\nglob\ngrep\nshell", "success -> #success\nerror -> #failure", test.configs)
detail, _ := startSource(t, ctx, source, workspace, func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
if err := os.Symlink("/etc", filepath.Join(workspace, "stray-link")); err != nil {
return stage.Result{}, err
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "looks fine"}}, nil
})
if detail.Status != test.status {
t.Fatalf("run %s %q", detail.Status, detail.Diagnostic)
}
if test.status == "failed" {
diagnostic := detail.Steps[0].Diagnostic
if !strings.Contains(diagnostic, "permission denied") || !strings.Contains(diagnostic, "added stray-link") || !strings.Contains(diagnostic, "allow_workspace_changes") {
t.Fatal(diagnostic)
}
}
})
}
}
func TestReadOnlyViolationIgnoresHarnessAndRunDirectories(t *testing.T) {
def := stage.Definition{Key: "review", Type: stage.ModelType, Configs: map[string]string{}}
changes := &protocol.StageFileChanges{Files: []protocol.FileChange{
{Path: ".claude-profile/.claude.json", Kind: "modified"},
{Path: "artifacts/x/out.md", Kind: "added"},
}}
ignored := []string{"/w/.claude-profile", "/w/artifacts/x"}
if v := readOnlyViolation(def, []string{"read", "shell"}, true, changes, "/w", ignored); v != "" {
t.Fatal(v)
}
changes.Files = append(changes.Files, protocol.FileChange{Path: "src/a.go", Kind: "modified"})
if v := readOnlyViolation(def, []string{"read", "shell"}, true, changes, "/w", ignored); !strings.Contains(v, "modified src/a.go") || strings.Contains(v, ".claude.json") {
t.Fatal(v)
}
for name, ok := range map[string]bool{
"edit tool": readOnlyViolation(def, []string{"edit", "shell"}, true, changes, "/w", nil) == "",
"no shell (cannot write)": readOnlyViolation(def, []string{"read"}, true, changes, "/w", nil) == "",
"no tools block (legacy bundle)": readOnlyViolation(def, nil, false, changes, "/w", nil) == "",
} {
if !ok {
t.Fatal(name, "was enforced")
}
}
}
+17 -8
View File
@@ -43,6 +43,20 @@ const deliveryCleanupTimeout = 10 * time.Second
// own `merge --ff-only`, which refuses without touching anything when a local
// change or untracked file would be overwritten.
func verifyDelivery(ctx context.Context, workspace string, access stage.LandingAccess, checks []string, commitMessage string) (string, error) {
return verifyDeliveryWith(ctx, workspace, access, commitMessage, func(ctx context.Context, candidate string) error {
for _, check := range checks {
if err := runDeliveryCheck(ctx, candidate, check); err != nil {
return err
}
}
return nil
})
}
// verifyDeliveryWith is verifyDelivery with the candidate checks supplied as
// a function of the fresh candidate worktree: a check stage records each
// command's result there instead of stopping at the first error.
func verifyDeliveryWith(ctx context.Context, workspace string, access stage.LandingAccess, commitMessage string, check func(context.Context, string) error) (string, error) {
lock, err := acquireDeliveryLock(ctx, access.LockPath)
if err != nil {
return "", err
@@ -82,7 +96,7 @@ func verifyDelivery(ctx context.Context, workspace string, access stage.LandingA
note = fmt.Sprintf("delivery gate: canonical main moved to %s; merged it into item %s as %s and re-ran checks on the merged tree", shortCommit(mainHead), shortCommit(itemHead), shortCommit(merged))
itemHead = merged
}
if err := runDeliveryCandidate(ctx, workspace, itemHead, checks); err != nil {
if err := runDeliveryCandidate(ctx, workspace, itemHead, check); err != nil {
if note != "" {
return note, fmt.Errorf("%s; %w", note, err)
}
@@ -199,7 +213,7 @@ func acquireDeliveryLock(ctx context.Context, path string) (*os.File, error) {
}
}
func runDeliveryCandidate(ctx context.Context, workspace, itemHead string, checks []string) error {
func runDeliveryCandidate(ctx context.Context, workspace, itemHead string, check func(context.Context, string) error) error {
candidate, err := os.MkdirTemp(filepath.Dir(workspace), ".pipelines-delivery-")
if err != nil {
return fmt.Errorf("create delivery candidate: %w", err)
@@ -212,12 +226,7 @@ func runDeliveryCandidate(ctx context.Context, workspace, itemHead string, check
return fmt.Errorf("create delivery candidate: %w: %s", err, strings.TrimSpace(string(output)))
}
defer cleanupDeliveryCandidate(workspace, candidate)
for _, check := range checks {
if err := runDeliveryCheck(ctx, candidate, check); err != nil {
return err
}
}
return nil
return check(ctx, candidate)
}
// cleanupDeliveryCandidate always uses its own bounded context: the stage context
+32 -4
View File
@@ -2250,6 +2250,8 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
budgetBefore = budgets[key].Snapshot()
stageCtx = stage.WithBudget(stageCtx, budgets[key])
}
repairs := &stage.RepairCounter{}
stageCtx = stage.WithRepairCounter(stageCtx, repairs)
snapshotCtx, snapshotCancel := context.WithTimeout(ctx, 5*time.Second)
before := filediff.Capture(snapshotCtx, workspace)
snapshotCancel()
@@ -2266,7 +2268,11 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
err = ctx.Err()
return
}
if r.execute != nil {
if stage.EffectiveType(def.Type) == stage.CheckType {
// The server runs a check stage's commands itself, in the run
// workspace or, for delivery, in a fresh candidate worktree.
result, err = r.runCheckStage(stageCtx, def, workspace, delivery, landing, id)
} else if r.execute != nil {
timeout, _ := stage.StageTimeout(def)
executeCtx, cancel := context.WithTimeout(stageCtx, timeout)
defer cancel()
@@ -2444,7 +2450,26 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
step.Output = stage.Values{"error": err.Error(), "stage": key, "input": input}
}
}
if err == nil && delivery && result.Outcome == "success" {
if err == nil {
// A stage without edit must leave the run directory as it found it;
// a shell is not a licence to write (allow_workspace_changes opts out).
ignored := append([]string{artifactsDir, visitTurn.PublicDir}, stage.HarnessStateDirs(workspaceEnv(stageCtx, workspace))...)
if violation := readOnlyViolation(def, tools, explicitTools, changes, workspace, ignored); violation != "" {
err = errors.New(violation)
log.Printf("run %d stage %s #%d: %s", id, key, sequence, violation)
step.Status = "failed"
step.Diagnostic = violation
step.Outcome = "error"
step.Output = stage.Values{"error": violation, "stage": key, "input": input}
if len(result.Output) > 0 {
step.Output["salvage"] = result.Output
}
}
}
if err == nil && stage.EffectiveType(def.Type) == stage.CheckType {
step.Verdict = checkVerdict(result.Output)
}
if err == nil && delivery && stage.EffectiveType(def.Type) == stage.ModelType && result.Outcome == "success" {
checks, checksErr := stage.DeliveryChecks(def)
if checksErr != nil {
err = checksErr
@@ -2488,7 +2513,10 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusRunning, CleanupUnconfirmed: true}, false)
return
}
step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads}
step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads, OutcomeRepairs: repairs.Count()}
if step.Control.OutcomeRepairs > 0 {
log.Printf("run %d stage %s #%d: outcome repair follow-up sent %d time(s)", id, key, sequence, step.Control.OutcomeRepairs)
}
if err == nil && selected.Limits != nil && state.visits[key] >= maxVisits {
for _, outcome := range selected.Limits.On {
if outcome == step.Outcome {
@@ -2535,7 +2563,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
// markdown body, which the field-map summariser reads as untrusted data and
// answers with an invented rationale; those steps get the honest read-time
// fallback instead.
if r.verdict != nil && !turnOutputOnly(step.Output) {
if r.verdict != nil && !turnOutputOnly(step.Output) && step.Verdict == nil {
reasonCtx, reasonCancel := context.WithTimeout(context.Background(), summarise.DefaultTimeout)
if line := r.verdict(reasonCtx, step.Output); line != "" && line != summarise.NoSummary {
step.Verdict = &protocol.StageVerdict{Reason: line, ReasonSource: protocol.VerdictReasonModel}
+6 -3
View File
@@ -190,12 +190,15 @@ func TestUISkipRunsModelOnAnyRecordedChange(t *testing.T) {
}
}
// TestUISkipPartialCaptureNeverSkips proves a visit whose capture was partial
// (here a protected .env file forces skipped>0) blocks the fallback even when
// (here a protected secrets/ directory, which is never walked, forces skipped>0;
// an untouched .env no longer does) blocks the fallback even when
// it recorded no file changes, and that inspect carries a run-level warning.
func TestUISkipPartialCaptureNeverSkips(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, ".env"), []byte("A=1\n"), 0o600); err != nil {
if err := os.MkdirAll(filepath.Join(dir, "secrets"), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "secrets", "token"), []byte("A=1\n"), 0o600); err != nil {
t.Fatal(err)
}
detail, visited, verdictCalls := runUISkipIn(t, uiReviewerSource(true), nil, dir)