Merge main into the engine loop improvements

Keep both intents: check stages, allow_workspace_changes, outcome repair
counts and Claude stage re-adoption from main beside the findings gate,
resume_session, applyLimitOn and exhaustion decisions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 14:24:27 +00:00
135 changed files with 7978 additions and 453 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
+75 -2
View File
@@ -122,10 +122,13 @@ func TestCleanupUnconfirmedReservesWorkspaceAcrossRecovery(t *testing.T) {
func TestWorkspaceOverlapIncludesParentsDescendantsAndSymlinks(t *testing.T) {
_, r, pipelineID := concurrentStore(t)
// One repository: its folder and a folder inside it are one shared tree.
workspace := t.TempDir()
child := filepath.Join(workspace, "child")
if err := os.Mkdir(child, 0700); err != nil {
t.Fatal(err)
for _, dir := range []string{filepath.Join(workspace, ".git"), child} {
if err := os.Mkdir(dir, 0700); err != nil {
t.Fatal(err)
}
}
alias := filepath.Join(t.TempDir(), "alias")
if err := os.Symlink(child, alias); err != nil {
@@ -176,3 +179,73 @@ func TestWorkspaceOverlapSeparatesNestedRepositories(t *testing.T) {
}
}
}
// Two folders outside any repository (the operator's ~/caplens and a sibling
// project folder under it) are not one tree merely because neither is in a
// repository: nested, they overlap only where the outer run's declared write
// paths reach the inner folder. The same folder always overlaps.
func TestWorkspaceOverlapNonRepositoryFolders(t *testing.T) {
hub := t.TempDir()
brief := filepath.Join(hub, "brief")
notes := filepath.Join(hub, "notes", "deep")
for _, dir := range []string{brief, notes} {
if err := os.MkdirAll(dir, 0700); err != nil {
t.Fatal(err)
}
}
paths := func(p ...string) func() []string { return func() []string { return p } }
for _, test := range []struct {
a, b string
aPaths, bPaths func() []string
want bool
}{
{hub, hub, nil, nil, true},
{brief, brief, nil, nil, true},
{hub, brief, nil, nil, false},
{brief, hub, nil, nil, false},
{brief, notes, nil, nil, false},
{hub, brief, paths("notes"), nil, false},
{hub, brief, paths("brief"), nil, true},
{hub, notes, paths("notes"), nil, true},
{hub, notes, paths("notes/deep/file.md"), nil, true},
{notes, hub, nil, paths("notes"), true},
{notes, hub, paths("notes"), nil, false}, // The inner run's paths do not reach out.
{hub, brief, paths("."), nil, true},
} {
if got := workspaceScopesOverlap(test.a, test.b, test.aPaths, test.bPaths); got != test.want {
t.Errorf("overlap(%s, %s) = %v, want %v", test.a, test.b, got, test.want)
}
}
// Nested repository rules stay: a repository inside a plain folder is its
// own tree whatever the folder's write paths.
repo := filepath.Join(hub, "repo")
if err := os.MkdirAll(filepath.Join(repo, ".git"), 0700); err != nil {
t.Fatal(err)
}
if workspaceScopesOverlap(hub, repo, paths("repo"), nil) {
t.Fatal("a repository inside a plain folder overlaps it")
}
// End to end: a scheduled brief in the hub is admitted while a run works in
// a sibling folder below it, and refused only when it declares a write
// path reaching that folder.
_, r, pipelineID := concurrentStore(t)
release := make(chan struct{})
defer close(release)
r.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
select {
case <-release:
case <-ctx.Done():
}
return stage.Result{Outcome: "success"}, nil
}
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "notes", Workspace: notes, Input: map[string]any{"prompt": "task"}}); err != nil {
t.Fatal(err)
}
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "brief-scoped", Workspace: hub, WritePaths: []string{"notes"}, Input: map[string]any{"prompt": "task"}}); err == nil || !strings.Contains(err.Error(), "already active") {
t.Fatal("a hub run writing into the active folder was admitted:", err)
}
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "brief", Workspace: hub, Input: map[string]any{"prompt": "task"}}); err != nil {
t.Fatal("a hub run was refused for a sibling folder's run:", err)
}
}
+25 -6
View File
@@ -23,12 +23,19 @@ import (
// re-enters that visit, attaches to the session, waits for it to settle (or
// reads the result it reached while the server was down) and continues the
// graph as if it had watched it;
// - a running Claude Code visit is re-adopted the same way: its CLI runs in
// its own session writing stream-json to a file (see
// stage.ClaudeStageClient), so the next process keeps reading that file
// where the CLI is, waits for it to exit, or reads the result it left
// while the server was down (an interrupted outcome repair follow-up is
// asked again);
// - a visit begun but never handed to a harness is marked interrupted and the
// same stage starts again (nothing was admitted, so nothing replays);
// - a run between visits continues with its next stage;
// - a session whose harness process is gone, or that belongs to a harness the
// server owned as a child (Pi, OpenCode V1), falls back to the previous
// behaviour: the run is interrupted, with the reason in its diagnostic.
// - a session whose harness process is gone (a Claude Code CLI that ended
// without a result), or that belongs to a harness the server owned as a
// child (Pi, OpenCode V1), falls back to the previous behaviour: the run
// is interrupted, with the reason in its diagnostic.
//
// Only an operator cancel (cancel_run) stops a stage session.
@@ -61,6 +68,10 @@ var stageServiceAlive = func(ctx context.Context, owner pipeline.SessionOwner) e
return opencode.ReferenceAlive(ctx, owner.Reference)
}
// claudeStageReattachable reports why a retained Claude Code stage session
// cannot be re-adopted (nil when it can). It is a seam for tests.
var claudeStageReattachable = stage.ClaudeStageReattachable
// interruptRecoveredSession stops a previously active session that start-up
// recovery does not re-adopt. It is a seam for tests.
var interruptRecoveredSession = func(ctx context.Context, owner pipeline.SessionOwner) error {
@@ -126,14 +137,22 @@ func planReattach(ctx context.Context, s *pipeline.Store) ([]reattachPlan, map[i
return nil, nil, nil, err
}
owner.RunID = row.ID
if owner.Backend == stage.ClaudeBackend {
// Claude Code stage CLIs run detached from the server: re-adopt
// one still running, or one that left its result while the
// server was down.
if reason := claudeStageReattachable(owner.Reference, owner.ID); reason != nil {
reasons[row.ID] = fmt.Sprintf("the Claude Code session running stage %s could not be reattached: %v", last.Stage, reason)
continue
}
plans = append(plans, reattachPlan{runID: row.ID, kind: reattachAdopt, step: last, owner: owner})
continue
}
if owner.Backend != "v2" {
name := "OpenCode V1"
if owner.Backend == "pi" {
name = "Pi"
}
if owner.Backend == stage.ClaudeBackend {
name = "Claude Code"
}
reasons[row.ID] = fmt.Sprintf("%s stage sessions belong to the stopped server process, so stage %s could not be reattached", name, last.Stage)
continue
}
+91
View File
@@ -294,3 +294,94 @@ func TestOperatorCancelStillStopsDetachingRun(t *testing.T) {
t.Fatalf("operator cancel did not stop the run: detached=%v %+v", detached.Load(), final)
}
}
// ownedClaudeStage is a first-process stage one whose Claude Code CLI
// (session claude-live) is still running, detached, at shutdown.
func ownedClaudeStage(ctx context.Context, s *pipeline.Store, id int64) (stage.Result, error) {
if err := s.RunSession(context.Background(), id, 1, "claude-live", true, stage.ClaudeBackend, "ref-claude"); err != nil {
return stage.Result{}, err
}
<-ctx.Done()
if stage.Detached(ctx) {
return stage.Result{}, stage.ErrDetached
}
return stage.Result{}, ctx.Err()
}
func seamClaudeReattachable(t *testing.T, reason error) *atomic.Value {
t.Helper()
asked := &atomic.Value{}
previous := claudeStageReattachable
claudeStageReattachable = func(reference, session string) error {
asked.Store(reference + " " + session)
return reason
}
t.Cleanup(func() { claudeStageReattachable = previous })
return asked
}
// TestClaudeStageRunContinuesAfterRestart: a Claude Code stage in flight at a
// restart is re-adopted from its retained session (never re-prompted, never
// interrupted) and the run continues to the next stage.
func TestClaudeStageRunContinuesAfterRestart(t *testing.T) {
interrupts := seamRestartRecovery(t, fmt.Errorf("the OpenCode probe must not be used for Claude"))
asked := seamClaudeReattachable(t, nil)
f := stopMidStage(t, ownedClaudeStage)
var resumed atomic.Value
r, s := f.restart(t, func(ctx context.Context, s *pipeline.Store, def stage.Definition) (stage.Result, error) {
if def.Key == "one" {
resumed.Store(stage.TakeResumeSession(ctx))
if err := s.RunSession(context.Background(), f.runID, 1, "claude-live", false, stage.ClaudeBackend, "ref-claude"); err != nil {
return stage.Result{}, err
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "Claude finished"}}, nil
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "next"}}, nil
})
if interrupts.Load() != 0 {
t.Fatal("start-up recovery interrupted a Claude Code stage that survived the restart")
}
if got, _ := asked.Load().(string); got != "ref-claude claude-live" {
t.Fatalf("reattachability asked about %q", got)
}
r.reattachRuns()
r.wg.Wait()
d, err := s.GetRun(context.Background(), f.runID)
if err != nil {
t.Fatal(err)
}
if got, _ := resumed.Load().(string); got != "claude-live" {
t.Fatalf("stage one was not re-adopted from its Claude session: %q", got)
}
if d.Status != "succeeded" || len(d.Steps) != 2 || d.Steps[0].Output["markdown"] != "Claude finished" {
t.Fatalf("run did not continue after the re-adopted Claude stage: %+v", d)
}
}
// TestClaudeStageGoneWithoutResultIsInterruptedWithReason: a Claude Code CLI
// that ended without a result while the server was down is not replayed; the
// run is interrupted, saying why.
func TestClaudeStageGoneWithoutResultIsInterruptedWithReason(t *testing.T) {
interrupts := seamRestartRecovery(t, nil)
seamClaudeReattachable(t, fmt.Errorf("Claude Code stopped while the server was restarting, before it reported a final result"))
f := stopMidStage(t, ownedClaudeStage)
r, s := f.restart(t, func(context.Context, *pipeline.Store, stage.Definition) (stage.Result, error) {
t.Error("a Claude stage without a result executed again")
return stage.Result{}, nil
})
r.reattachRuns()
r.wg.Wait()
d, err := s.GetRun(context.Background(), f.runID)
if err != nil {
t.Fatal(err)
}
if d.Status != "interrupted" || !strings.Contains(d.Diagnostic, "Claude Code session running stage one could not be reattached") || !strings.Contains(d.Diagnostic, "before it reported a final result") {
t.Fatalf("lost Claude stage lacks a clear reason: status=%s run=%q", d.Status, d.Diagnostic)
}
if interrupts.Load() != 1 {
t.Fatalf("the leftover Claude group was not confirmed stopped: %d", interrupts.Load())
}
if owners, _ := s.ActiveSessionOwners(context.Background()); len(owners) != 0 {
t.Fatalf("the lost session still blocks recovery: %+v", owners)
}
}
+115 -27
View File
@@ -320,7 +320,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
return nil, err
}
if existing == 0 {
if err := r.checkWorkspaceFree(workspace); err != nil {
if err := r.checkWorkspaceFree(workspace, request.WritePaths...); err != nil {
r.mu.Unlock()
return nil, err
}
@@ -344,7 +344,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
// Another run may have reserved this workspace while the title was
// generated, so re-check before reserving it; a race on the request key is
// handled by the store's idempotent insert.
if err := r.checkAdmissionWorkspace(workspace, existing); err != nil {
if err := r.checkAdmissionWorkspace(workspace, existing, request.WritePaths...); err != nil {
r.mu.Unlock()
return nil, err
}
@@ -381,7 +381,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
request.Input["pwd"] = workspace
recheck := r.ctx.Err()
if recheck == nil {
recheck = r.checkAdmissionWorkspace(workspace, existing)
recheck = r.checkAdmissionWorkspace(workspace, existing, request.WritePaths...)
}
if recheck != nil {
r.mu.Unlock()
@@ -544,9 +544,9 @@ var runSettleRead = func(r *runner, ctx context.Context, id int64) (*protocol.Ru
// storage maintenance may have removed a clean inactive tree while an
// admission was generating its title, so it is checked under the same lock
// removal takes. Callers must hold r.mu.
func (r *runner) checkAdmissionWorkspace(workspace string, existing int64) error {
func (r *runner) checkAdmissionWorkspace(workspace string, existing int64, writePaths ...string) error {
if existing == 0 {
if err := r.checkWorkspaceFree(workspace); err != nil {
if err := r.checkWorkspaceFree(workspace, writePaths...); err != nil {
return err
}
}
@@ -558,14 +558,30 @@ func (r *runner) checkAdmissionWorkspace(workspace string, existing int64) error
// checkWorkspaceFree refuses a run when an active or cleanup-unconfirmed run
// reserves an overlapping resolved workspace. Callers must hold r.mu.
func (r *runner) checkWorkspaceFree(workspace string) error {
return r.checkWorkspaceFreeExcept(workspace, 0)
// writePaths are the new run's declared write paths (they decide an overlap
// only between nested folders outside any repository).
func (r *runner) checkWorkspaceFree(workspace string, writePaths ...string) error {
return r.checkWorkspaceFreeExcept(workspace, 0, writePaths...)
}
func (r *runner) checkWorkspaceFreeExcept(workspace string, ownGate int64) error {
func (r *runner) checkWorkspaceFreeExcept(workspace string, ownGate int64, writePaths ...string) error {
own := func() []string { return writePaths }
// pathsOf reads a reserving run's declared write paths only when needed.
pathsOf := func(id int64) func() []string {
return func() []string {
read, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 5*time.Second)
defer cancel()
paths, err := r.store.RunWritePaths(read, id)
if err != nil {
// Unknown scope: keep the whole folder reserved (fail closed).
return []string{"."}
}
return paths
}
}
for id, entry := range r.active {
if workspacesOverlap(entry.workspace, workspace) {
return fmt.Errorf("run %d is already active in %s, which overlaps this run's workspace %s; wait for run %d to finish or use a different workspace (for example another checkout of the repository)", id, entry.workspace, workspace, id)
if workspaceScopesOverlap(entry.workspace, workspace, pathsOf(id), own) {
return &workspaceBusyError{runID: id, message: fmt.Sprintf("run %d is already active in %s, which overlaps this run's workspace %s; wait for run %d to finish or use a different workspace (for example another checkout of the repository)", id, entry.workspace, workspace, id)}
}
}
check, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 5*time.Second)
@@ -575,35 +591,76 @@ func (r *runner) checkWorkspaceFreeExcept(workspace string, ownGate int64) error
return fmt.Errorf("read pending export workspace reservations: %w", err)
}
for id, reserved := range reservations {
if id != ownGate && workspacesOverlap(reserved, workspace) {
return fmt.Errorf("run %d is awaiting its session export; workspace %s remains reserved", id, reserved)
if id != ownGate && workspaceScopesOverlap(reserved, workspace, pathsOf(id), own) {
return &workspaceBusyError{runID: id, message: fmt.Sprintf("run %d is awaiting its session export; workspace %s remains reserved", id, reserved)}
}
}
return nil
}
// workspaceBusyError refuses an admission because another run (runID)
// reserves an overlapping workspace; waiting can clear it.
type workspaceBusyError struct {
runID int64
message string
}
func (e *workspaceBusyError) Error() string { return e.message }
// workspacesOverlap reports whether two resolved workspaces are the same
// tree or nested in one another within the same repository. A folder that
// merely holds separate repositories (a hub such as ~/project with clones
// under repos/) does not overlap a run inside one of those repositories, and
// neither do two different repositories nested in one another: each run
// works in its own repository.
// works in its own repository. Two folders outside any repository are not one
// shared tree either: nested, they overlap only where the outer run declared
// write paths reaching the inner folder (see workspaceScopesOverlap).
func workspacesOverlap(a, b string) bool {
within := func(parent, child string) bool {
rel, err := filepath.Rel(parent, child)
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator))
}
return workspaceScopesOverlap(a, b, nil, nil)
}
// workspaceScopesOverlap is workspacesOverlap with each workspace's declared
// write paths (relative to it). They matter only for two nested folders
// outside any repository; a nil lookup means "declared none".
func workspaceScopesOverlap(a, b string, aPaths, bPaths func() []string) bool {
switch {
case filepath.Clean(a) == filepath.Clean(b):
return true
case within(a, b):
return repositoryRoot(b) == repositoryRoot(a)
case within(b, a):
return repositoryRoot(a) == repositoryRoot(b)
case pathAtOrBelow(a, b):
return nestedWorkspacesOverlap(a, b, aPaths)
case pathAtOrBelow(b, a):
return nestedWorkspacesOverlap(b, a, bPaths)
}
return false
}
// nestedWorkspacesOverlap decides for an inner workspace below outer.
func nestedWorkspacesOverlap(outer, inner string, outerPaths func() []string) bool {
root := repositoryRoot(outer)
if repositoryRoot(inner) != root {
return false // Different repositories: each run works in its own.
}
if root != "" {
return true // The same repository is one shared tree.
}
if outerPaths == nil {
return false
}
for _, path := range outerPaths() {
target := filepath.Join(outer, path)
if pathAtOrBelow(target, inner) || pathAtOrBelow(inner, target) {
return true
}
}
return false
}
// pathAtOrBelow reports whether child is parent or below it.
func pathAtOrBelow(parent, child string) bool {
rel, err := filepath.Rel(parent, child)
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator))
}
// repositoryRoot is the nearest directory at or above dir holding a .git
// entry (a repository or a linked worktree), or "" outside any repository.
func repositoryRoot(dir string) string {
@@ -1080,7 +1137,7 @@ func (r *runner) decide(request protocol.Message) (*protocol.RunDetail, error) {
return nil, fmt.Errorf("run %d is awaiting session export, not a human decision", detail.ID)
}
if detail.Status == protocol.RunStatusWaiting {
if err := r.checkWorkspaceFree(detail.Workspace); err != nil {
if err := r.checkWorkspaceFree(detail.Workspace, detail.WritePaths...); err != nil {
r.mu.Unlock()
return nil, err
}
@@ -2308,6 +2365,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()
@@ -2324,7 +2383,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()
@@ -2352,7 +2415,10 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
client.Transcript = piClient.Transcript
} else if modelConfig.Harness == stage.ClaudeBackend {
claudeClient := &stage.ClaudeStageClient{Directory: workspace, Tools: tools, WritePaths: request.WritePaths, ArtifactsDir: artifactsDir, Skills: def.Skills}
if def.Configs["resume_session"] == "true" && adopted == nil && state.visits[key] > 1 {
if adopted != nil {
// Follow the CLI the previous process left (see run_reattach.go).
claudeClient.Reference = adopted.owner.Reference
} else if def.Configs["resume_session"] == "true" && state.visits[key] > 1 {
// A loop visit continues the stage's previous session.
claudeClient.ResumeSessionID = state.sessions[key]
}
@@ -2502,7 +2568,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
@@ -2546,7 +2631,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)
}
parkExhausted := false
if err == nil {
parkExhausted = applyLimitOn(&step, selected, state.visits[key], maxVisits)
@@ -2588,7 +2676,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}
+109 -8
View File
@@ -1,12 +1,16 @@
package server
import (
"context"
"errors"
"fmt"
"log"
"os"
"time"
"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 (r *runner) scheduleLoop() {
@@ -89,6 +93,10 @@ func (r *runner) claimSchedule(item protocol.SavedSchedule, now time.Time, recov
if err != nil {
return err
}
if claimed && status == "skipped_missed" {
name := scheduleLabel(item)
go r.scheduleNotice(item, due, "skipped", "Scheduled run skipped: "+name, fmt.Sprintf("%s was due at %s while the server was not running, so that run was skipped.", name, due.Local().Format("15:04 on 2 Jan")), "")
}
if !claimed || status != "claimed" {
return nil
}
@@ -100,21 +108,114 @@ func (r *runner) claimSchedule(item protocol.SavedSchedule, now time.Time, recov
return nil
}
// admitScheduled starts one claimed schedule's run and records the outcome.
// scheduleBusyRetry is how often, and for how long after its due time, a
// scheduled admission whose workspace another run holds is tried again
// (the limit counts from the first attempt).
// PIPELINES_SCHEDULE_BUSY_RETRY_EVERY and PIPELINES_SCHEDULE_BUSY_RETRY_FOR
// (Go durations; FOR=0 disables waiting) override the defaults.
var scheduleBusyRetry = func() (every, limit time.Duration) {
every, limit = 5*time.Minute, 2*time.Hour
if value, err := time.ParseDuration(os.Getenv("PIPELINES_SCHEDULE_BUSY_RETRY_EVERY")); err == nil && value > 0 {
every = value
}
if value, err := time.ParseDuration(os.Getenv("PIPELINES_SCHEDULE_BUSY_RETRY_FOR")); err == nil && value >= 0 {
limit = value
}
return every, limit
}
// scheduleNoticePriority is ntfy's "low" priority.
const scheduleNoticePriority = 2
// admitScheduled starts one claimed schedule's run and records the outcome in
// the schedule's history. A workspace another run holds delays the admission
// instead of skipping it: it is tried again every few minutes for a bounded
// time, recorded as "delayed" meanwhile. The operator is told, at low
// priority, when a scheduled run is delayed and when one is skipped.
func (r *runner) admitScheduled(item protocol.SavedSchedule, due time.Time) {
request := protocol.Message{PipelineID: item.PipelineID, Version: item.Version, RequestKey: fmt.Sprintf("saved-schedule:%d:%d", item.ID, due.UnixNano()), Input: item.Input, Workspace: item.Workspace, WritePaths: item.WritePaths, AllowTools: item.AllowTools, Model: item.Model, StageModels: item.StageModels, NotifyMode: item.NotifyMode, Title: item.Title, OutputFormat: item.OutputFormat}
run, err := r.startWithSchedule(request, &pipeline.ScheduleAdmission{ID: item.ID, Revision: item.Revision, Due: due, Name: item.Name})
every, limit := scheduleBusyRetry()
started := time.Now()
deadline := started.Add(limit)
name := scheduleLabel(item)
diagnostic := ""
status := "started"
var runID int64
if err != nil {
status = "skipped"
diagnostic = err.Error()
} else if run != nil {
runID = run.ID
for attempt := 1; ; attempt++ {
run, err := r.startWithSchedule(request, &pipeline.ScheduleAdmission{ID: item.ID, Revision: item.Revision, Due: due, Name: item.Name})
if err == nil {
status, diagnostic = "started", ""
if run != nil {
runID = run.ID
}
if attempt > 1 {
diagnostic = fmt.Sprintf("started after waiting %s for a busy workspace", time.Since(started).Round(time.Second))
}
break
}
status, diagnostic = "skipped", err.Error()
var busy *workspaceBusyError
if !errors.As(err, &busy) {
break
}
if time.Now().Add(every).After(deadline) {
if attempt > 1 {
diagnostic = fmt.Sprintf("gave up after waiting %s for a busy workspace: %s", time.Since(started).Round(time.Second), diagnostic)
}
break
}
if attempt == 1 {
r.scheduleNotice(item, due, "delayed", "Scheduled run delayed: "+name,
fmt.Sprintf("%s is waiting for run #%d to free its workspace; it is tried again every %s until %s.", name, busy.runID, every, deadline.Local().Format("15:04")), runAttentionClick(busy.runID))
}
delayed := fmt.Sprintf("waiting for a busy workspace (attempt %d; retrying every %s until %s): %s", attempt, every, deadline.UTC().Format(time.RFC3339), err.Error())
if err := r.store.FinishSavedSchedule(r.ctx, item.ID, due, "delayed", delayed); err != nil {
log.Printf("schedule id=%d record delay: %v", item.ID, err)
}
log.Printf("schedule id=%d pipeline=%d due=%s delayed: %s", item.ID, item.PipelineID, due.Format(time.RFC3339), delayed)
timer := time.NewTimer(every)
select {
case <-timer.C:
continue
case <-r.ctx.Done():
timer.Stop()
diagnostic = "the server stopped while this run waited for a busy workspace: " + diagnostic
}
break
}
if err := r.store.FinishSavedSchedule(r.ctx, item.ID, due, status, diagnostic); err != nil {
save, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 10*time.Second)
if err := r.store.FinishSavedSchedule(save, item.ID, due, status, diagnostic); err != nil {
log.Printf("schedule id=%d record admission: %v", item.ID, err)
}
cancel()
if status == "skipped" {
r.scheduleNotice(item, due, "skipped", "Scheduled run skipped: "+name, name+" did not start: "+diagnostic, "")
}
log.Printf("schedule id=%d pipeline=%d version=%d due=%s status=%s run=%d %s", item.ID, item.PipelineID, item.Version, due.Format(time.RFC3339), status, runID, diagnostic)
}
// scheduleLabel names a schedule in a notice.
func scheduleLabel(item protocol.SavedSchedule) string {
if name := singleLine(item.Name); name != "" {
return truncateUTF8(name, 120)
}
return fmt.Sprintf("Schedule %d", item.ID)
}
// scheduleNotice tells the operator, at low priority, through the app
// notification stream and (when enabled) ntfy, that a scheduled run was
// delayed or skipped.
func (r *runner) scheduleNotice(item protocol.SavedSchedule, due time.Time, event, title, message, click string) {
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 30*time.Second)
defer cancel()
title, message = truncateUTF8(singleLine(title), 256), truncateUTF8(singleLine(message), 2000)
r.notes.record(ctx, pipeline.AppNotificationRecord{AppNotification: protocol.AppNotification{
ID: fmt.Sprintf("schedule:%d:%d:%s", item.ID, due.UnixNano(), event), Kind: protocol.NotificationSchedule,
Title: title, Message: message, Click: click, Priority: scheduleNoticePriority, Tags: []string{}, Group: fmt.Sprintf("schedule:%d", item.ID)}})
if !chatAttentionConfigured() || !ntfyEnabled(ctx, r.settingsStore()) {
return
}
if _, err := ntfyPublish(stage.WithNtfyPriority(ctx, scheduleNoticePriority), "system", title, message, "", nil, click); err != nil {
log.Printf("schedule id=%d %s notice: %v", item.ID, event, err)
}
}
+136
View File
@@ -0,0 +1,136 @@
package server
import (
"context"
"strings"
"testing"
"time"
"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 scheduleNotices(t *testing.T, s *pipeline.Store) []protocol.AppNotification {
t.Helper()
active, _, err := s.ActiveAppNotifications(context.Background(), "", time.Now())
if err != nil {
t.Fatal(err)
}
var notices []protocol.AppNotification
for _, n := range active {
if n.Kind == protocol.NotificationSchedule {
notices = append(notices, n)
}
}
return notices
}
func waitOccurrence(t *testing.T, s *pipeline.Store, id int64, due time.Time, want string) (string, int64) {
t.Helper()
deadline := time.Now().Add(10 * time.Second)
for {
status, diagnostic, run, err := s.SavedScheduleOccurrence(context.Background(), id, due)
if err == nil && status == want {
return diagnostic, run
}
if time.Now().After(deadline) {
t.Fatalf("occurrence status %q (%q, %v), want %q", status, diagnostic, err, want)
}
time.Sleep(5 * time.Millisecond)
}
}
// A scheduled run whose workspace another run holds is delayed, not skipped:
// it is recorded as delayed, the operator is told at low priority, and it
// starts once the workspace is free.
func TestScheduledRunWaitsForABusyWorkspace(t *testing.T) {
seamScheduleBusyRetry(t, 20*time.Millisecond, time.Hour)
ctx, s, r, pid := scheduleFixture(t)
r.notes = newAppNotifier(s)
workspace := t.TempDir()
busy := saveTestSchedule(t, ctx, s, pid, "busy", workspace, "1h", time.Now())
brief := saveTestSchedule(t, ctx, s, pid, "Daily brief", workspace, "1h", time.Now())
release := make(chan struct{})
entered := make(chan struct{}, 2)
r.execute = func(ctx context.Context, _ stage.Definition, input stage.Values) (stage.Result, error) {
entered <- struct{}{}
if prompt, _ := input["prompt"].(string); prompt == "busy" {
<-release
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Done"}}, nil
}
if err := r.scheduleTick(dueOf(t, busy), false); err != nil {
t.Fatal(err)
}
<-entered
due := dueOf(t, brief)
if err := r.scheduleTick(due, false); err != nil {
t.Fatal(err)
}
diagnostic, _ := waitOccurrence(t, s, brief.ID, due, "delayed")
if !strings.Contains(diagnostic, "busy workspace") || !strings.Contains(diagnostic, "already active") {
t.Fatalf("delay diagnostic %q", diagnostic)
}
notices := scheduleNotices(t, s)
if len(notices) != 1 || notices[0].Priority != 2 || !strings.Contains(notices[0].Title, "delayed") || !strings.Contains(notices[0].Title, "Daily brief") {
t.Fatalf("delay notices %+v", notices)
}
close(release)
diagnostic, run := waitOccurrence(t, s, brief.ID, due, "started")
r.scheduleAdmissions.Wait()
r.wg.Wait()
if run == 0 || !strings.Contains(diagnostic, "started after waiting") {
t.Fatalf("delayed run not admitted: run=%d %q", run, diagnostic)
}
runs, err := s.ListRuns(ctx)
if err != nil || len(runs) != 2 {
t.Fatalf("runs %+v %v", runs, err)
}
}
// Waiting is bounded: past the limit the occurrence is skipped, saying why,
// and the operator is told.
func TestScheduledRunGivesUpOnABusyWorkspace(t *testing.T) {
seamScheduleBusyRetry(t, 20*time.Millisecond, 150*time.Millisecond)
ctx, s, r, pid := scheduleFixture(t)
r.notes = newAppNotifier(s)
workspace := t.TempDir()
busy := saveTestSchedule(t, ctx, s, pid, "busy", workspace, "1h", time.Now())
brief := saveTestSchedule(t, ctx, s, pid, "Daily brief", workspace, "1h", time.Now())
release := make(chan struct{})
defer close(release)
entered := make(chan struct{}, 2)
r.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
entered <- struct{}{}
select {
case <-release:
case <-ctx.Done():
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Done"}}, nil
}
if err := r.scheduleTick(dueOf(t, busy), false); err != nil {
t.Fatal(err)
}
<-entered
due := dueOf(t, brief)
if claimed, err := s.ClaimSavedSchedule(ctx, *brief, due, due.Add(time.Hour), "claimed"); err != nil || !claimed {
t.Fatal(claimed, err)
}
r.admitScheduled(*brief, due)
diagnostic, run := waitOccurrence(t, s, brief.ID, due, "skipped")
if run != 0 || !strings.Contains(diagnostic, "gave up after waiting") {
t.Fatalf("skip diagnostic %q run=%d", diagnostic, run)
}
notices := scheduleNotices(t, s)
var titles []string
for _, n := range notices {
titles = append(titles, n.Title)
if n.Priority != 2 {
t.Fatalf("schedule notice is not low priority: %+v", n)
}
}
if len(notices) != 2 || !strings.Contains(strings.Join(titles, "|"), "skipped") {
t.Fatalf("notices %v", titles)
}
}
+10
View File
@@ -201,7 +201,17 @@ func TestScheduleDeletionDoesNotCancelAdmittedRun(t *testing.T) {
}
}
// seamScheduleBusyRetry sets how a scheduled admission waits for a busy
// workspace (limit 0: it is skipped at once, as before delays existed).
func seamScheduleBusyRetry(t *testing.T, every, limit time.Duration) {
t.Helper()
previous := scheduleBusyRetry
scheduleBusyRetry = func() (time.Duration, time.Duration) { return every, limit }
t.Cleanup(func() { scheduleBusyRetry = previous })
}
func TestSavedScheduleRecoveryAndOverlap(t *testing.T) {
seamScheduleBusyRetry(t, time.Minute, 0)
ctx, s, r, pid := scheduleFixture(t)
item := saveTestSchedule(t, ctx, s, pid, "task", t.TempDir(), "1m", time.Now())
due := dueOf(t, item)
+1 -1
View File
@@ -35,7 +35,7 @@ func (r *runner) resumeExportGates(ctx context.Context) error {
r.mu.Unlock()
return err
}
if err := r.checkWorkspaceFreeExcept(d.Workspace, id); err != nil {
if err := r.checkWorkspaceFreeExcept(d.Workspace, id, d.WritePaths...); err != nil {
r.mu.Unlock()
continue
}
+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)