Files
pipelines/internal/server/loop_control_test.go
T
alan 34b8b94223 Engine: run findings ledger, findings gate, loop continuation, larger memory, loop lint, retry partial work, resume_session
- Runner-owned findings ledger per run: stages report a # findings section
  (new items and F<n> status changes); stable IDs, persisted (run_loop_state),
  in RunDetail.findings, findings.md, memory.md, inspect.
- type=findings gate stage routes open/clear on the ledger mechanically.
- retry --extra-visits N [--stage KEY] continues an exhausted loop; limits
  on_exhausted=decide parks the run on accept/continue/abort.
- Essential memory cap 20 KB, task never truncated, handoff and open findings
  ahead of the outcome ledger.
- Lint rejects limits.on outcomes on forward edges; warns on ineffective
  limits and resume_session.
- A resumed retry carries the failed visit's output.md and private/ under
  previous-attempt/.
- resume_session=true resumes a Claude stage's previous session on loop visits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 14:22:28 +00:00

239 lines
10 KiB
Go

package server
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"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"
)
// loopSource is implement -> review, with review's rejected looping back.
// extraReview is spliced into the review stage (limits etc.).
func loopSource(extraReview string) string {
source := pipeline.Template([]string{"implement", "review"}, true)
source = strings.Replace(source, "# stage review", "# stage review\n\n"+extraReview, 1)
return strings.Replace(source, "success -> #success", "success -> #success\nrejected -> implement", 1)
}
func loopRunner(t *testing.T, source string) (*runner, *pipeline.Store, int64) {
t.Helper()
ctx := context.Background()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "run.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { store.Close() })
if _, err := store.Submit(ctx, "loop", source); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
r, err := newRunnerAt(ctx, store, t.TempDir())
if err != nil {
t.Fatal(err)
}
return r, store, items[0].ID
}
func markdown(text string) stage.Result {
outcome := strings.TrimSpace(strings.SplitN(strings.TrimPrefix(text, "# outcome\n"), "\n", 2)[0])
return stage.Result{Outcome: outcome, Output: stage.Values{"markdown": text}}
}
// TestFindingsLedgerAndGateRouteTheLoop runs implement -> review -> triage
// (a findings gate) and checks the ledger: stable IDs, status changes from a
// later visit, the ledger in memory.md and findings.md, a dismissed finding a
// reviewer re-raises staying dismissed, and the gate routing mechanically.
func TestFindingsLedgerAndGateRouteTheLoop(t *testing.T) {
source := pipeline.Template([]string{"implement", "review"}, true)
source = strings.Replace(source, "success -> #success", "success -> triage", 1)
source += "# stage triage\n\n```limits\n{\"max_visits\":3}\n```\n\n```configs\ntype=findings\nseverity=important\norigin=introduced\n```\n\n```edges\nopen -> implement\nclear -> #success\n```\n"
r, store, pipelineID := loopRunner(t, source)
calls := map[string]int{}
var implementMemory, implementLedgerFile string
r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
calls[def.Key]++
switch {
case def.Key == "implement" && calls["implement"] == 2:
memory, _ := os.ReadFile(def.Turn.Memory)
implementMemory = string(memory)
ledger, _ := os.ReadFile(filepath.Join(def.Turn.Dir, "findings.md"))
implementLedgerFile = string(ledger)
return markdown("# outcome\nsuccess\n\n# handoff\nFixed F1.\n\n# findings\n- F1 fixed: added the eviction\n- F2 dismissed: style only\n"), nil
case def.Key == "implement":
return markdown("# outcome\nsuccess\n\n# handoff\nDone.\n"), nil
case calls["review"] == 1:
return markdown("# outcome\nsuccess\n\n# handoff\nTwo findings.\n\n# findings\n- important introduced cache.go:42: eviction never runs\n- important pre-existing util.go:7: odd helper\n- nit introduced cache.go:1: naming\n"), nil
default:
// Re-raises the dismissed F2: it must stay dismissed.
return markdown("# outcome\nsuccess\n\n# handoff\nLooks good.\n\n# findings\n- important pre-existing util.go:7: odd helper\n"), nil
}
}
run := startRun(t, r, pipelineID, "findings")
detail, err := store.GetRun(context.Background(), run.ID)
if err != nil {
t.Fatal(err)
}
if detail.Status != "succeeded" || calls["implement"] != 2 || calls["review"] != 2 {
t.Fatalf("status %s calls %v diag %q", detail.Status, calls, detail.Diagnostic)
}
var routes []string
for _, step := range detail.Steps {
if step.Stage == "triage" {
routes = append(routes, step.Outcome+"->"+step.Target)
}
}
if strings.Join(routes, ",") != "open->implement,clear->#success" {
t.Fatalf("gate routes %v", routes)
}
status := map[string]string{}
for _, item := range detail.Findings {
status[item.ID] = item.Status
}
if len(detail.Findings) != 3 || status["F1"] != "fixed" || status["F2"] != "dismissed" || status["F3"] != "open" {
t.Fatalf("ledger %+v", detail.Findings)
}
if !strings.Contains(implementMemory, "## Findings ledger (runner-owned)") || !strings.Contains(implementMemory, "F1 · important · introduced · cache.go:42 — eviction never runs") || !strings.Contains(implementMemory, "never re-raise") {
t.Fatalf("implement memory lacks the ledger:\n%s", implementMemory)
}
if !strings.Contains(implementLedgerFile, "# Findings ledger") || !strings.Contains(implementLedgerFile, "F2 · important · pre-existing") {
t.Fatalf("findings.md:\n%s", implementLedgerFile)
}
}
// TestExhaustedLoopAsksTheOperator covers on_exhausted=decide: the last allowed
// review asks for another round, the run waits on a decision, "continue" grants
// one more visit and "accept" finishes the run.
func TestExhaustedLoopAsksTheOperator(t *testing.T) {
r, store, pipelineID := loopRunner(t, loopSource("```limits\n{\"max_visits\":2,\"on\":[\"rejected\"],\"on_exhausted\":\"decide\"}\n```"))
calls := map[string]int{}
r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
calls[def.Key]++
if def.Key == "review" {
return markdown("# outcome\nrejected\n\n# handoff\nStill wrong.\n"), nil
}
return markdown("# outcome\nsuccess\n\n# handoff\nDone.\n"), nil
}
run := startRun(t, r, pipelineID, "exhausted")
ctx := context.Background()
detail, _ := store.GetRun(ctx, run.ID)
last := detail.Steps[len(detail.Steps)-1]
if detail.Status != protocol.RunStatusWaiting || last.Status != protocol.StepStatusWaiting || last.Stage != "review" || protocol.ExhaustedInfo(last.Output) == nil {
t.Fatalf("not waiting on an exhaustion decision: %s %+v", detail.Status, last)
}
if got := strings.Join(protocol.WaitingOptions(last.Output), ","); got != "abort,accept,continue" {
t.Fatalf("options %s", got)
}
if _, err := r.decide(protocol.Message{RunID: run.ID, Option: "continue"}); err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, _ = store.GetRun(ctx, run.ID)
if detail.Status != protocol.RunStatusWaiting || calls["review"] != 3 || calls["implement"] != 3 {
t.Fatalf("one more round did not run: %s calls %v", detail.Status, calls)
}
if detail.VisitGrants["review"] != 1 || detail.VisitGrants["implement"] != 1 {
t.Fatalf("grants %v", detail.VisitGrants)
}
if _, err := r.decide(protocol.Message{RunID: run.ID, Option: "accept"}); err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, _ = store.GetRun(ctx, run.ID)
if detail.Status != "succeeded" {
t.Fatalf("accept did not finish the run: %s %q", detail.Status, detail.Diagnostic)
}
}
// TestRetryWithExtraVisitsContinuesTheLoop retries a run whose review loop was
// exhausted: without extra visits the retry fails again at once; with
// --extra-visits it continues at the implementer and the next review approves.
func TestRetryWithExtraVisitsContinuesTheLoop(t *testing.T) {
r, store, pipelineID := loopRunner(t, loopSource("```limits\n{\"max_visits\":2,\"on\":[\"rejected\"]}\n```"))
calls := map[string]int{}
approve := false
r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
calls[def.Key]++
if def.Key == "review" {
if approve {
return markdown("# outcome\nsuccess\n\n# handoff\nApproved.\n"), nil
}
return markdown("# outcome\nrejected\n\n# handoff\nStill wrong.\n\n# findings\n- important introduced a.go:1: still wrong\n"), nil
}
return markdown("# outcome\nsuccess\n\n# handoff\nDone.\n"), nil
}
run := startRun(t, r, pipelineID, "extra")
ctx := context.Background()
detail, _ := store.GetRun(ctx, run.ID)
if detail.Status != "failed" || calls["review"] != 2 {
t.Fatalf("source run: %s %v", detail.Status, calls)
}
if _, err := r.retry(protocol.Message{RunID: run.ID, RequestKey: "x", RetryExtraVisits: 9}); err == nil {
t.Fatal("extra visits over the bound accepted")
}
if _, err := r.retry(protocol.Message{RunID: run.ID, RequestKey: "y", RetryExtraVisits: 1, RetryExtraStage: "nope"}); err == nil {
t.Fatal("unknown extra-visits stage accepted")
}
approve = true
retried, err := r.retry(protocol.Message{RunID: run.ID, RequestKey: "retry-extra", RetryExtraVisits: 1})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, _ = store.GetRun(ctx, retried.ID)
if detail.Status != "succeeded" || calls["implement"] != 3 || calls["review"] != 3 {
t.Fatalf("retry: %s %q calls %v", detail.Status, detail.Diagnostic, calls)
}
if detail.Steps[0].Stage != "implement" || detail.VisitGrants["review"] != 1 {
t.Fatalf("retry did not continue at the implementer with a review grant: %+v %v", detail.Steps[0], detail.VisitGrants)
}
if len(detail.Findings) != 1 || detail.Findings[0].ID != "F1" {
t.Fatalf("retry did not inherit the ledger: %+v", detail.Findings)
}
}
// TestRetryCarriesThePartialWorkOfTheFailedVisit checks that the retried
// visit receives the failed visit's private/ files and output.md under
// previous-attempt/ and that its input.md names them.
func TestRetryCarriesThePartialWorkOfTheFailedVisit(t *testing.T) {
r, store, pipelineID := loopRunner(t, pipeline.Template([]string{"implement"}, true))
fail := true
var retriedInput, carried string
r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
if fail {
_ = os.WriteFile(filepath.Join(def.Turn.Private, "notes.md"), []byte("half done: parser rewritten"), 0o600)
_ = os.WriteFile(def.Turn.Output, []byte("# outcome\nsuccess\n\npartial"), 0o600)
return stage.Result{}, errors.New("timed out")
}
input, _ := os.ReadFile(def.Turn.Input)
retriedInput = string(input)
notes, _ := os.ReadFile(filepath.Join(def.Turn.Dir, "previous-attempt", "private", "notes.md"))
carried = string(notes)
return markdown("# outcome\nsuccess\n\n# handoff\nFinished.\n"), nil
}
run := startRun(t, r, pipelineID, "carry")
fail = false
retried, err := r.retry(protocol.Message{RunID: run.ID, RequestKey: "carry-retry"})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, _ := store.GetRun(context.Background(), retried.ID)
if detail.Status != "succeeded" {
t.Fatalf("retry %s %q", detail.Status, detail.Diagnostic)
}
if carried != "half done: parser rewritten" {
t.Fatalf("private notes not carried: %q", carried)
}
for _, want := range []string{"# Previous attempt", "## Partial work from the failed attempt", "- output.md (", "- private/notes.md ("} {
if !strings.Contains(retriedInput, want) {
t.Fatalf("input.md missing %q:\n%s", want, retriedInput)
}
}
}