Merge main (findings ledger, loop continuation) into usage-limit branch
Keeps the findings ledger, extra visits and on_exhausted=decide alongside the run budget, failure classes, quota parking and error-loop backoff. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -88,7 +88,7 @@ func (r *runner) scanArtifacts(runID int64, sequence int, directory string, publ
|
||||
}
|
||||
// Mandatory runtime evidence must not disappear behind hundreds of private
|
||||
// captures/public deliverables in the bounded inventory.
|
||||
for _, name := range []string{"input.md", "memory.md", "history.md", "output.md", "session.html"} {
|
||||
for _, name := range []string{"input.md", "memory.md", "history.md", "findings.md", "output.md", "session.html"} {
|
||||
full := path.Join(rel, name)
|
||||
if info, err := root.Lstat(full); err == nil && info.Mode().IsRegular() && info.Mode()&fs.ModeSymlink == 0 && info.Size() <= maxArtifactFileBytes {
|
||||
add(full, name, info)
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/findings"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"git.a-wan.net/alan/pipelines/internal/turn"
|
||||
)
|
||||
|
||||
// Loop control: per-stage visit caps (raised by grants), the findings ledger,
|
||||
// mechanical findings gates and operator decisions on exhausted loops.
|
||||
|
||||
const (
|
||||
// maxStageVisits is the global per-stage visit cap before grants.
|
||||
maxStageVisits = 5
|
||||
// maxRunSteps is the global step cap before grants.
|
||||
maxRunSteps = 30
|
||||
// maxExtraVisits bounds one grant (a retry's --extra-visits).
|
||||
maxExtraVisits = 5
|
||||
// maxRunStepsWithGrants is the absolute step cap however much is granted.
|
||||
maxRunStepsWithGrants = 120
|
||||
)
|
||||
|
||||
func graphHasStage(g protocol.Graph, key string) bool {
|
||||
for _, s := range g.Stages {
|
||||
if s.Key == key {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// visitCaps returns a stage's effective max_visits and hard per-stage cap,
|
||||
// both raised by the extra visits granted to it.
|
||||
func (s *runState) visitCaps(selected protocol.Stage) (limit, hard int) {
|
||||
limit = maxStageVisits
|
||||
if selected.Limits != nil {
|
||||
limit = selected.Limits.MaxVisits
|
||||
}
|
||||
extra := s.grants[selected.Key]
|
||||
return limit + extra, maxStageVisits + extra
|
||||
}
|
||||
|
||||
// stepLimit is the run's total step cap: 30 plus, for every granted visit,
|
||||
// room for one more pass through the graph, bounded.
|
||||
func (s *runState) stepLimit(graph protocol.Graph) int {
|
||||
total := maxRunSteps
|
||||
for _, extra := range s.grants {
|
||||
total += extra * max(len(graph.Stages), 1)
|
||||
}
|
||||
return min(total, maxRunStepsWithGrants)
|
||||
}
|
||||
|
||||
// grant adds extra visits to each named stage.
|
||||
func (s *runState) grant(stages []string, extra int) {
|
||||
if s.grants == nil {
|
||||
s.grants = map[string]int{}
|
||||
}
|
||||
for _, key := range stages {
|
||||
s.grants[key] += extra
|
||||
}
|
||||
}
|
||||
|
||||
// exhaustedContinuation turns the last step of a run that a visit cap stopped
|
||||
// into the checkpoint that continues its loop: the stage the routing was
|
||||
// heading to, with the stopped step's output as its input. ok is false when
|
||||
// the run did not stop on a cap.
|
||||
func exhaustedContinuation(last protocol.RunStep) (protocol.RunStep, bool) {
|
||||
if last.Status != "completed" {
|
||||
return last, false
|
||||
}
|
||||
target := last.Target
|
||||
if last.Control != nil && last.Control.LimitReached && last.Control.ModelTarget != "" {
|
||||
target = last.Control.ModelTarget
|
||||
}
|
||||
if target == "" || protocol.IsTerminal(target) {
|
||||
return last, false
|
||||
}
|
||||
input := last.Output
|
||||
if input == nil {
|
||||
input = map[string]any{}
|
||||
}
|
||||
return protocol.RunStep{Sequence: last.Sequence + 1, Stage: target, Status: "failed", Target: protocol.FailureEnd, Input: input}, true
|
||||
}
|
||||
|
||||
// exhaustedStages are the non-human stages whose next visit their caps refuse,
|
||||
// plus next (the stage the run continues with) when nothing else is.
|
||||
func exhaustedStages(graph protocol.Graph, state *runState, next string) []string {
|
||||
var out []string
|
||||
for _, declared := range graph.Stages {
|
||||
if stage.EffectiveType(declared.Type) == stage.HumanType {
|
||||
continue
|
||||
}
|
||||
limit, hard := state.visitCaps(declared)
|
||||
if visits := state.visits[declared.Key]; visits > 0 && (visits >= limit || visits >= hard) {
|
||||
out = append(out, declared.Key)
|
||||
}
|
||||
}
|
||||
if len(out) == 0 && next != "" {
|
||||
out = append(out, next)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// applyLimitOn applies a stage's limits.on on its last allowed visit: a listed
|
||||
// outcome is kept but routed to #failure, or, with on_exhausted=decide, keeps
|
||||
// its route and the caller parks the run on an operator decision (park true).
|
||||
func applyLimitOn(step *protocol.RunStep, selected protocol.Stage, visit, maxVisits int) (park bool) {
|
||||
if selected.Limits == nil || visit < maxVisits || step.Target == "" || protocol.IsTerminal(step.Target) {
|
||||
return false
|
||||
}
|
||||
for _, outcome := range selected.Limits.On {
|
||||
if outcome != step.Outcome {
|
||||
continue
|
||||
}
|
||||
step.Control.LimitReached = true
|
||||
step.Control.ModelTarget = step.Target
|
||||
if decidesOnExhaustion(selected) {
|
||||
return true
|
||||
}
|
||||
step.Target = protocol.FailureEnd
|
||||
step.Diagnostic = fmt.Sprintf("Pipelines stopped %s after %d visits on outcome %s", selected.Key, maxVisits, step.Outcome)
|
||||
return false
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isExhaustionStep reports whether a recorded step is a runner-created
|
||||
// exhaustion decision rather than a stage visit.
|
||||
func isExhaustionStep(step protocol.RunStep) bool {
|
||||
return protocol.ExhaustedInfo(step.Output) != nil
|
||||
}
|
||||
|
||||
func decidesOnExhaustion(s protocol.Stage) bool {
|
||||
return s.Limits != nil && s.Limits.OnExhausted == "decide"
|
||||
}
|
||||
|
||||
// parkExhausted parks the run on an operator decision because stage selected
|
||||
// exhausted its visits: accept the work as it is (accept_to, default
|
||||
// #success), continue for one more round (continueTo, with one more visit
|
||||
// granted) or abort. It mirrors a human stage's wait: one waiting step and no
|
||||
// live goroutine; the decision resumes the run through decide.
|
||||
func (r *runner) parkExhausted(ctx context.Context, id int64, name, workspace string, state *runState, sequence int, selected protocol.Stage, visit, maxVisits int, continueTo string) error {
|
||||
accept := protocol.SuccessEnd
|
||||
if selected.Limits != nil && selected.Limits.AcceptTo != "" {
|
||||
accept = selected.Limits.AcceptTo
|
||||
}
|
||||
targets := map[string]any{protocol.ExhaustedAccept: accept, protocol.ExhaustedContinue: continueTo, protocol.ExhaustedAbort: protocol.FailureEnd}
|
||||
prompt := fmt.Sprintf("Stage %s used its %d allowed visits and the loop is not finished. Choose accept to take the work as it is (continues to %s), continue for one more round (one more visit; continues to %s), or abort to fail the run.", selected.Key, maxVisits, accept, continueTo)
|
||||
options := []string{protocol.ExhaustedAbort, protocol.ExhaustedAccept, protocol.ExhaustedContinue}
|
||||
evidence := protocol.NewWaitingEvidence(prompt, options)
|
||||
evidence[protocol.ExhaustedKey] = map[string]any{"stage": selected.Key, "visit": visit, "max_visits": maxVisits, "targets": targets}
|
||||
if err := r.store.BeginStep(ctx, id, sequence, selected.Key, state.input); err != nil {
|
||||
return err
|
||||
}
|
||||
state.nextSequence = sequence + 1
|
||||
r.mu.Lock()
|
||||
if err := r.store.MarkWaiting(ctx, id, sequence, selected.Key, evidence); err != nil {
|
||||
r.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
r.emitRun(protocol.RunEventFrame{
|
||||
RunID: id,
|
||||
Workspace: workspace,
|
||||
Status: protocol.RunStatusWaiting,
|
||||
CurrentStage: selected.Key,
|
||||
CompletedSteps: state.completed,
|
||||
Step: &protocol.RunStepDelta{Sequence: sequence, Stage: selected.Key, Status: protocol.StepStatusWaiting},
|
||||
}, false)
|
||||
delete(r.active, id)
|
||||
r.mu.Unlock()
|
||||
r.deliverRunNotificationBatch(time.Now(), 1)
|
||||
return nil
|
||||
}
|
||||
|
||||
// grantForDecision records the extra visit a "continue" exhaustion decision
|
||||
// allows: one more visit for the exhausted stage and for the stage the loop
|
||||
// continues with.
|
||||
func (r *runner) grantForDecision(ctx context.Context, detail *protocol.RunDetail, step protocol.RunStep) {
|
||||
info := protocol.ExhaustedInfo(step.Output)
|
||||
if info == nil || step.Outcome != protocol.ExhaustedContinue {
|
||||
return
|
||||
}
|
||||
stages := []string{}
|
||||
if key, ok := info["stage"].(string); ok && key != "" {
|
||||
stages = append(stages, key)
|
||||
}
|
||||
if step.Target != "" && !protocol.IsTerminal(step.Target) && (len(stages) == 0 || stages[0] != step.Target) {
|
||||
stages = append(stages, step.Target)
|
||||
}
|
||||
for _, key := range stages {
|
||||
grants, err := r.store.AddRunVisitGrant(ctx, detail.ID, key, 1)
|
||||
if err != nil {
|
||||
log.Printf("run %d: grant a visit to %s: %v", detail.ID, key, err)
|
||||
continue
|
||||
}
|
||||
detail.VisitGrants = grants
|
||||
}
|
||||
}
|
||||
|
||||
// recordFindings folds a completed visit's "# findings" section into the run's
|
||||
// ledger and persists it. A ledger write failure is logged, never fatal: the
|
||||
// stage's own output keeps the findings.
|
||||
func (r *runner) recordFindings(id int64, state *runState, step protocol.RunStep) {
|
||||
markdown, _ := step.Output["markdown"].(string)
|
||||
report := findings.Parse(markdown)
|
||||
if len(report.New) == 0 && len(report.Changes) == 0 {
|
||||
return
|
||||
}
|
||||
ledger, outcome := findings.Apply(state.findings, report, step.Stage, step.Sequence)
|
||||
state.findings = ledger
|
||||
if len(outcome.Ignored) > 0 {
|
||||
log.Printf("run %d stage %s #%d: findings ignored: %s", id, step.Stage, step.Sequence, strings.Join(outcome.Ignored, "; "))
|
||||
}
|
||||
r.persistFindings(id, ledger)
|
||||
}
|
||||
|
||||
func (r *runner) persistFindings(id int64, ledger []protocol.Finding) {
|
||||
save, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := r.store.SetRunFindings(save, id, ledger); err != nil {
|
||||
log.Printf("run %d: save findings ledger: %v", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *runner) persistGrants(id int64, grants map[string]int) {
|
||||
save, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := r.store.SetRunVisitGrants(save, id, grants); err != nil {
|
||||
log.Printf("run %d: save visit grants: %v", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
// findingsGateStep evaluates a findings stage against the ledger.
|
||||
func findingsGateStep(def stage.Definition, state *runState, sequence int) protocol.RunStep {
|
||||
gate, _ := stage.FindingsGate(def)
|
||||
matched := gate.Matching(state.findings)
|
||||
outcome := stage.FindingsClear
|
||||
reason := fmt.Sprintf("No open findings at %s or above (origin %s).", gate.MinSeverity, gate.Origin)
|
||||
ids := make([]string, 0, len(matched))
|
||||
for _, item := range matched {
|
||||
ids = append(ids, item.ID)
|
||||
}
|
||||
if len(matched) > 0 {
|
||||
outcome = stage.FindingsOpen
|
||||
reason = fmt.Sprintf("%d open finding(s) at %s or above (origin %s): %s.", len(matched), gate.MinSeverity, gate.Origin, strings.Join(ids, ", "))
|
||||
}
|
||||
return protocol.RunStep{
|
||||
Sequence: sequence,
|
||||
Stage: def.Key,
|
||||
Status: "completed",
|
||||
Outcome: outcome,
|
||||
Output: stage.Values{"summary": reason, "findings": ids},
|
||||
Target: def.Edges[outcome],
|
||||
Verdict: &protocol.StageVerdict{Reason: reason, ReasonSource: protocol.VerdictReasonFallback},
|
||||
}
|
||||
}
|
||||
|
||||
// writeFindingsFile writes the visit's findings.md (the whole ledger) next to
|
||||
// memory.md when the run has a ledger.
|
||||
func writeFindingsFile(paths turn.Paths, ledger []protocol.Finding) error {
|
||||
if len(ledger) == 0 {
|
||||
return nil
|
||||
}
|
||||
name := filepath.Join(paths.TurnDir, "findings.md")
|
||||
if err := os.WriteFile(name, []byte(findings.RenderFile(ledger)), 0o600); err != nil {
|
||||
return fmt.Errorf("write %s: %w", name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// Bounds on the partial work a retried visit inherits from the failed one.
|
||||
const (
|
||||
carryMaxFiles = 200
|
||||
carryMaxFileBytes = 1 << 20
|
||||
carryMaxTotal = 8 << 20
|
||||
carryDir = "previous-attempt"
|
||||
)
|
||||
|
||||
// carryPartialWork copies a failed visit's output.md and private/ files
|
||||
// (bounded) into the retried visit's turn directory under previous-attempt/
|
||||
// and returns the markdown that tells the stage about them, or "" when there
|
||||
// was nothing to carry. Symlinks and special files are skipped; the source is
|
||||
// read through os.Root so nothing outside the failed turn is reachable.
|
||||
func carryPartialWork(sourceTurn, targetTurn string) string {
|
||||
source, err := os.OpenRoot(sourceTurn)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer source.Close()
|
||||
var names []string
|
||||
if info, err := source.Lstat("output.md"); err == nil && info.Mode().IsRegular() {
|
||||
names = append(names, "output.md")
|
||||
}
|
||||
skipped := 0
|
||||
_ = fs.WalkDir(source.FS(), "private", func(name string, entry fs.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
return nil
|
||||
}
|
||||
if entry.Type().IsRegular() {
|
||||
names = append(names, name)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
sort.Strings(names[min(1, len(names)):])
|
||||
target := filepath.Join(targetTurn, carryDir)
|
||||
var copied []string
|
||||
total := int64(0)
|
||||
for _, name := range names {
|
||||
if len(copied) >= carryMaxFiles {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
info, err := source.Lstat(name)
|
||||
if err != nil || !info.Mode().IsRegular() || info.Size() > carryMaxFileBytes || total+info.Size() > carryMaxTotal {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
if err := copyCarried(source, name, filepath.Join(target, filepath.FromSlash(name))); err != nil {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
total += info.Size()
|
||||
copied = append(copied, fmt.Sprintf("%s (%d bytes)", name, info.Size()))
|
||||
}
|
||||
if len(copied) == 0 {
|
||||
return ""
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("\n## Partial work from the failed attempt\n\n")
|
||||
fmt.Fprintf(&b, "The failed visit's output.md and private/ files are copied, read-only, into %s:\n\n", target)
|
||||
for _, line := range copied {
|
||||
b.WriteString("- " + line + "\n")
|
||||
}
|
||||
if skipped > 0 {
|
||||
fmt.Fprintf(&b, "- … %d more not copied (over the size or count bound)\n", skipped)
|
||||
}
|
||||
b.WriteString("\nReuse what is still valid instead of redoing it.\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func copyCarried(source *os.Root, name, destination string) error {
|
||||
if path.Clean(name) != name || strings.HasPrefix(name, "../") {
|
||||
return errors.New("invalid name")
|
||||
}
|
||||
src, err := source.OpenFile(name, os.O_RDONLY|syscall.O_NOFOLLOW, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer src.Close()
|
||||
if err := os.MkdirAll(filepath.Dir(destination), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
dst, err := os.OpenFile(destination, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, copyErr := io.Copy(dst, io.LimitReader(src, carryMaxFileBytes))
|
||||
if closeErr := dst.Close(); copyErr == nil {
|
||||
copyErr = closeErr
|
||||
}
|
||||
return copyErr
|
||||
}
|
||||
+158
-29
@@ -16,6 +16,7 @@ import (
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/claude"
|
||||
"git.a-wan.net/alan/pipelines/internal/filediff"
|
||||
"git.a-wan.net/alan/pipelines/internal/findings"
|
||||
"git.a-wan.net/alan/pipelines/internal/harness"
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
@@ -448,7 +449,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
|
||||
}
|
||||
}
|
||||
if request.RetrySource > 0 && request.RetryMode != "restart" {
|
||||
checkpoint, checkpointErr := r.retrySourceCheckpointSelected(request.RetrySource, d, request.RetryStage, request.RetryVisit, request.RetryInput)
|
||||
checkpoint, checkpointErr := r.retrySourceCheckpointSelected(request.RetrySource, d, request.RetryStage, request.RetryVisit, request.RetryInput, request.RetryExtraVisits)
|
||||
if checkpointErr != nil {
|
||||
return nil, checkpointErr
|
||||
}
|
||||
@@ -863,10 +864,10 @@ func retryStageContractEqual(left, right protocol.Stage) bool {
|
||||
}
|
||||
|
||||
func (r *runner) retrySourceCheckpoint(sourceID int64, pinned *protocol.PipelineDetail) (retryCheckpoint, error) {
|
||||
return r.retrySourceCheckpointSelected(sourceID, pinned, "", 0, nil)
|
||||
return r.retrySourceCheckpointSelected(sourceID, pinned, "", 0, nil, 0)
|
||||
}
|
||||
|
||||
func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.PipelineDetail, selectedStage string, selectedVisit int, override map[string]any) (retryCheckpoint, error) {
|
||||
func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.PipelineDetail, selectedStage string, selectedVisit int, override map[string]any, extraVisits int) (retryCheckpoint, error) {
|
||||
source, err := r.store.GetRun(r.ctx, sourceID)
|
||||
if err != nil {
|
||||
return retryCheckpoint{}, err
|
||||
@@ -882,6 +883,13 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.
|
||||
return retryCheckpoint{}, fmt.Errorf("retry source %d has no failed stage checkpoint", sourceID)
|
||||
}
|
||||
failed := source.Steps[len(source.Steps)-1]
|
||||
if extraVisits > 0 && selectedStage == "" && !interrupted {
|
||||
// More visits for an exhausted loop: continue the loop where the cap
|
||||
// stopped it instead of re-running the visit that hit it.
|
||||
if next, ok := exhaustedContinuation(failed); ok {
|
||||
failed = next
|
||||
}
|
||||
}
|
||||
if interrupted && selectedStage == "" {
|
||||
// A server stop interrupts a run mid-visit (the visit is recorded as
|
||||
// interrupted, with the input it began with) or between visits (the
|
||||
@@ -951,6 +959,9 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.
|
||||
// stage's memory bindings must be resolved from the original prefix before
|
||||
// this override is applied at invocation time.
|
||||
handoff = map[string]any{"input": failed.Input, "override": override, "sequence": failed.Sequence, "stage": failed.Stage, "visit": failed.Sequence}
|
||||
if extraVisits > 0 {
|
||||
handoff["extra_visits"] = extraVisits
|
||||
}
|
||||
prefix, prefixRecords, prefixErr := r.retryPrefix(sourceID, source, failed.Sequence)
|
||||
if prefixErr != nil {
|
||||
return retryCheckpoint{}, prefixErr
|
||||
@@ -1076,6 +1087,20 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) {
|
||||
if mode != "resume" && mode != "restart" {
|
||||
return nil, fmt.Errorf("retry mode must be resume or restart")
|
||||
}
|
||||
if request.RetryExtraVisits < 0 || request.RetryExtraVisits > maxExtraVisits {
|
||||
return nil, fmt.Errorf("extra visits must be from 1 to %d", maxExtraVisits)
|
||||
}
|
||||
if request.RetryExtraVisits > 0 && (mode != "resume" || request.RetryStage != "" || request.RetryVisit > 0) {
|
||||
return nil, fmt.Errorf("extra visits continue the exhausted loop; they cannot be combined with --mode=restart or a selected stage visit")
|
||||
}
|
||||
if request.RetryExtraStage != "" {
|
||||
if request.RetryExtraVisits == 0 {
|
||||
return nil, fmt.Errorf("an extra-visits stage needs extra visits")
|
||||
}
|
||||
if !graphHasStage(original.Graph, request.RetryExtraStage) {
|
||||
return nil, fmt.Errorf("stage %q is not part of run %d", request.RetryExtraStage, original.ID)
|
||||
}
|
||||
}
|
||||
version := original.Version
|
||||
if request.RetryVersion > 0 {
|
||||
version = request.RetryVersion
|
||||
@@ -1085,7 +1110,7 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) {
|
||||
return nil, err
|
||||
}
|
||||
if mode == "resume" {
|
||||
if _, err := r.retrySourceCheckpointSelected(original.ID, d, request.RetryStage, request.RetryVisit, request.RetryInput); err != nil {
|
||||
if _, err := r.retrySourceCheckpointSelected(original.ID, d, request.RetryStage, request.RetryVisit, request.RetryInput, request.RetryExtraVisits); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -1098,7 +1123,7 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) {
|
||||
if budgetUSD == 0 && original.Budget != nil && original.Budget.Source == "run" {
|
||||
budgetUSD = original.Budget.LimitUSD
|
||||
}
|
||||
return r.start(protocol.Message{PipelineID: original.PipelineID, Version: version, RequestKey: request.RequestKey, RetryMode: mode, RetrySource: original.ID, RetryStage: request.RetryStage, RetryVisit: request.RetryVisit, RetryInput: request.RetryInput, Workspace: original.Workspace, Input: original.Input, AllowTools: original.AllowTools, WritePaths: original.WritePaths, Model: original.Model, StageModels: original.StageModels, NotifyMode: notifyMode, OutputFormat: original.OutputFormat, QuotaPolicy: request.QuotaPolicy, BudgetUSD: budgetUSD}, original.ID)
|
||||
return r.start(protocol.Message{PipelineID: original.PipelineID, Version: version, RequestKey: request.RequestKey, RetryMode: mode, RetrySource: original.ID, RetryStage: request.RetryStage, RetryVisit: request.RetryVisit, RetryInput: request.RetryInput, RetryExtraVisits: request.RetryExtraVisits, RetryExtraStage: request.RetryExtraStage, Workspace: original.Workspace, Input: original.Input, AllowTools: original.AllowTools, WritePaths: original.WritePaths, Model: original.Model, StageModels: original.StageModels, NotifyMode: notifyMode, OutputFormat: original.OutputFormat, QuotaPolicy: request.QuotaPolicy, BudgetUSD: budgetUSD}, original.ID)
|
||||
}
|
||||
|
||||
func (r *runner) cancel(id int64) error {
|
||||
@@ -1179,6 +1204,8 @@ func (r *runner) decide(request protocol.Message) (*protocol.RunDetail, error) {
|
||||
return nil, err
|
||||
}
|
||||
if applied {
|
||||
// "continue" on an exhausted loop grants the visit it needs.
|
||||
r.grantForDecision(r.ctx, detail, step)
|
||||
// Re-seed the identity so the resumed frames (this one and the resumed
|
||||
// loop's) carry it even after a restart, when no creation was observed.
|
||||
r.rememberRunIdentity(detail.ID, identityOfRunSummary(detail.RunSummary))
|
||||
@@ -1220,7 +1247,7 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
|
||||
r.finishRunState(id, d.Name, workspace, "failed", "error", err.Error(), 0, 0, "", nil)
|
||||
return
|
||||
}
|
||||
checkpoint, err := r.retrySourceCheckpointSelected(request.RetrySource, d, request.RetryStage, request.RetryVisit, request.RetryInput)
|
||||
checkpoint, err := r.retrySourceCheckpointSelected(request.RetrySource, d, request.RetryStage, request.RetryVisit, request.RetryInput, request.RetryExtraVisits)
|
||||
if err != nil {
|
||||
r.finishRunState(id, d.Name, workspace, "failed", "error", err.Error(), 0, 0, "", nil)
|
||||
return
|
||||
@@ -1251,6 +1278,30 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
|
||||
r.finishRunState(id, d.Name, workspace, "failed", "error", err.Error(), 0, 0, "", nil)
|
||||
return
|
||||
}
|
||||
// The ledger as it stood before the retried visit, the source's grants
|
||||
// plus any new ones, and the failed visit's partial work.
|
||||
state.findings = findings.Before(source.Findings, checkpoint.failed.Sequence)
|
||||
if len(state.findings) > 0 {
|
||||
r.persistFindings(id, state.findings)
|
||||
}
|
||||
for key, extra := range source.VisitGrants {
|
||||
state.grant([]string{key}, extra)
|
||||
}
|
||||
if request.RetryExtraVisits > 0 {
|
||||
stages := []string{request.RetryExtraStage}
|
||||
if request.RetryExtraStage == "" {
|
||||
stages = exhaustedStages(d.Graph, state, state.key)
|
||||
}
|
||||
state.grant(stages, request.RetryExtraVisits)
|
||||
}
|
||||
if len(state.grants) > 0 {
|
||||
r.persistGrants(id, state.grants)
|
||||
}
|
||||
for _, step := range source.Steps {
|
||||
if step.Sequence == checkpoint.failed.Sequence && step.Stage == checkpoint.failed.Stage && step.Status != "completed" {
|
||||
state.carryFrom = r.turnPaths(source.ID, step.Sequence, step.Stage).TurnDir
|
||||
}
|
||||
}
|
||||
r.runLoop(ctx, id, d.Graph, d.Name, workspace, request, state)
|
||||
return
|
||||
}
|
||||
@@ -1412,6 +1463,15 @@ type runState struct {
|
||||
// failure, so the same one twice in a row stops the loop.
|
||||
errorLoops map[string]int
|
||||
lastHarness map[string]string
|
||||
// findings is the run's findings ledger; grants are extra visits per stage
|
||||
// (loop_state.go). sessions is each stage's latest harness session, which
|
||||
// a resume_session stage continues on its next visit.
|
||||
findings []protocol.Finding
|
||||
grants map[string]int
|
||||
sessions map[string]string
|
||||
// carryFrom is the failed source visit's turn directory whose private/
|
||||
// and output.md the retried visit receives; prepareTurn consumes it.
|
||||
carryFrom string
|
||||
}
|
||||
|
||||
func newRunState(key string, input stage.Values) *runState {
|
||||
@@ -1429,7 +1489,24 @@ func rebuildRunState(detail *protocol.RunDetail, decided protocol.RunStep) *runS
|
||||
}
|
||||
publicSeen := map[string]bool{}
|
||||
state.priorBudgets = map[string]stage.BudgetSnapshot{}
|
||||
state.findings = append([]protocol.Finding(nil), detail.Findings...)
|
||||
for key, extra := range detail.VisitGrants {
|
||||
state.grant([]string{key}, extra)
|
||||
}
|
||||
for _, step := range detail.Steps {
|
||||
if isExhaustionStep(step) {
|
||||
// A runner-created exhaustion decision is not a stage visit.
|
||||
if step.Sequence >= state.nextSequence {
|
||||
state.nextSequence = step.Sequence + 1
|
||||
}
|
||||
continue
|
||||
}
|
||||
if step.SessionID != "" {
|
||||
if state.sessions == nil {
|
||||
state.sessions = map[string]string{}
|
||||
}
|
||||
state.sessions[step.Stage] = step.SessionID
|
||||
}
|
||||
// The runtime stamps this cumulative snapshot on every executed model
|
||||
// visit. Reusing it preserves per-stage limits across export recovery.
|
||||
var audit struct {
|
||||
@@ -1487,6 +1564,9 @@ func rebuildRetryState(detail *protocol.RunDetail, failed protocol.RunStep, hand
|
||||
if step.Sequence >= failed.Sequence {
|
||||
break
|
||||
}
|
||||
if isExhaustionStep(step) {
|
||||
continue
|
||||
}
|
||||
state.visits[step.Stage]++
|
||||
added := publicArtifacts(step.Artifacts, publicSeen)
|
||||
if step.Status == "completed" {
|
||||
@@ -1561,7 +1641,7 @@ func (r *runner) retryPrefix(sourceID int64, source *protocol.RunDetail, failedS
|
||||
}
|
||||
publicBySequence := retryPublicBySequence(source, failedSequence)
|
||||
for _, step := range source.Steps {
|
||||
if step.Sequence >= failedSequence || step.Status != "completed" {
|
||||
if step.Sequence >= failedSequence || step.Status != "completed" || isExhaustionStep(step) {
|
||||
continue
|
||||
}
|
||||
prefix[step.Stage] = step.Output
|
||||
@@ -2057,7 +2137,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
effectiveModels = resolved
|
||||
}
|
||||
runBudget := r.runBudget(ctx, id)
|
||||
for sequence := state.nextSequence; sequence <= 30; sequence++ {
|
||||
for sequence := state.nextSequence; sequence <= state.stepLimit(graph); sequence++ {
|
||||
if ctx.Err() != nil {
|
||||
canceled()
|
||||
return
|
||||
@@ -2094,23 +2174,29 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
}
|
||||
}
|
||||
isHuman := stage.EffectiveType(def.Type) == stage.HumanType
|
||||
maxVisits := 5
|
||||
if selected.Limits != nil {
|
||||
maxVisits = selected.Limits.MaxVisits
|
||||
}
|
||||
// Both caps include the extra visits granted to the stage.
|
||||
maxVisits, hardVisits := state.visitCaps(selected)
|
||||
// Validate the next visit without consuming it. An already-exhausted
|
||||
// stage must not begin work it can never execute.
|
||||
if !isHuman {
|
||||
if state.visits[key]+1 > 5 {
|
||||
state.failureClass = protocol.FailureLoopExhausted
|
||||
if !isHuman && (state.visits[key]+1 > hardVisits || state.visits[key]+1 > maxVisits) {
|
||||
if decidesOnExhaustion(selected) {
|
||||
// on_exhausted=decide: ask the operator instead of failing.
|
||||
if err := r.parkExhausted(ctx, id, name, workspace, state, sequence, selected, state.visits[key], min(maxVisits, hardVisits), key); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
canceled()
|
||||
return
|
||||
}
|
||||
finish("failed", "error", err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
state.failureClass = protocol.FailureLoopExhausted
|
||||
if state.visits[key]+1 > hardVisits {
|
||||
finish("failed", "error", "stage visit budget exceeded")
|
||||
return
|
||||
}
|
||||
if state.visits[key]+1 > maxVisits {
|
||||
state.failureClass = protocol.FailureLoopExhausted
|
||||
finish("failed", "error", fmt.Sprintf("stage %s visit limit reached (%d)", key, maxVisits))
|
||||
return
|
||||
}
|
||||
finish("failed", "error", fmt.Sprintf("stage %s visit limit reached (%d)", key, maxVisits))
|
||||
return
|
||||
}
|
||||
// adopted is the visit a previous server process began and left running
|
||||
// across its restart: its step row, turn files and session already exist.
|
||||
@@ -2215,6 +2301,34 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
r.deliverRunNotificationBatch(time.Now(), 1)
|
||||
return
|
||||
}
|
||||
if stage.EffectiveType(def.Type) == stage.FindingsType {
|
||||
// A findings gate routes mechanically on the run's ledger: no
|
||||
// model, no capture, no turn files.
|
||||
step := findingsGateStep(def, state, sequence)
|
||||
step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads}
|
||||
park := applyLimitOn(&step, selected, state.visits[key], maxVisits)
|
||||
status, outcome, diagnostic, terminal, finishErr := r.finishStage(id, name, workspace, selected, state, step)
|
||||
if finishErr != nil {
|
||||
finish("failed", "error", finishErr.Error())
|
||||
return
|
||||
}
|
||||
state.recordTurn(step, nil)
|
||||
state.completed++
|
||||
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusRunning, CurrentStage: key, CompletedSteps: state.completed,
|
||||
Step: &protocol.RunStepDelta{Sequence: step.Sequence, Stage: step.Stage, Status: step.Status, Outcome: step.Outcome, Target: step.Target, Diagnostic: step.Diagnostic}}, false)
|
||||
if terminal {
|
||||
finish(status, outcome, diagnostic)
|
||||
return
|
||||
}
|
||||
if park {
|
||||
if err := r.parkExhausted(ctx, id, name, workspace, state, state.nextSequence, selected, state.visits[key], maxVisits, step.Target); err != nil {
|
||||
finish("failed", "error", err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
state.key = step.Target
|
||||
continue
|
||||
}
|
||||
// Server skip fallback: a stage that declares a `skipped` route is
|
||||
// short-circuited only when the run's evidence is complete and empty
|
||||
// (autoSkipEligible, ui_surface.go): every visit recorded a complete
|
||||
@@ -2390,6 +2504,9 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
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]
|
||||
}
|
||||
claudeClient.OnOwnership = func(session, reference string, active bool) error {
|
||||
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
@@ -2642,18 +2759,13 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
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 {
|
||||
step.Control.LimitReached = true
|
||||
step.Control.ModelTarget = step.Target
|
||||
step.Target = protocol.FailureEnd
|
||||
step.Diagnostic = fmt.Sprintf("Pipelines stopped %s after %d visits on outcome %s", key, maxVisits, step.Outcome)
|
||||
}
|
||||
}
|
||||
parkExhausted := false
|
||||
if err == nil {
|
||||
parkExhausted = applyLimitOn(&step, selected, state.visits[key], maxVisits)
|
||||
}
|
||||
if panicked {
|
||||
step.Target = protocol.FailureEnd
|
||||
parkExhausted = false
|
||||
}
|
||||
switch {
|
||||
case step.Control.LimitReached:
|
||||
@@ -2734,6 +2846,9 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
if artifactsDir != "" {
|
||||
state.artifactDirs = append(state.artifactDirs, strconv.Itoa(sequence))
|
||||
}
|
||||
if stage.EffectiveType(def.Type) == stage.ModelType {
|
||||
r.recordFindings(id, state, step)
|
||||
}
|
||||
} else if quota.rerun {
|
||||
// The visit runs again on the switched account with its own
|
||||
// input, told that the limit interrupted it; it does not count.
|
||||
@@ -2768,10 +2883,24 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
canceled()
|
||||
return
|
||||
}
|
||||
if stageSession != "" {
|
||||
if state.sessions == nil {
|
||||
state.sessions = map[string]string{}
|
||||
}
|
||||
state.sessions[key] = stageSession
|
||||
}
|
||||
if terminal {
|
||||
finish(status, outcome, diagnostic)
|
||||
return
|
||||
}
|
||||
if parkExhausted {
|
||||
// on_exhausted=decide: the last allowed visit asked for another
|
||||
// round; the operator decides instead of the run failing.
|
||||
if err := r.parkExhausted(ctx, id, name, workspace, state, state.nextSequence, selected, state.visits[key], maxVisits, step.Target); err != nil {
|
||||
finish("failed", "error", err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
r.checkRunBudget(id, name, runBudget)
|
||||
if step.Status == "completed" {
|
||||
delete(state.errorLoops, key)
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/findings"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"git.a-wan.net/alan/pipelines/internal/turn"
|
||||
@@ -71,6 +72,15 @@ func (r *runner) prepareTurn(paths turn.Paths, state *runState, retryInput stage
|
||||
input += "\n" + state.previousAttempt
|
||||
state.previousAttempt = ""
|
||||
}
|
||||
if state.carryFrom != "" {
|
||||
// The failed visit's partial work, copied into this visit's turn.
|
||||
input += carryPartialWork(state.carryFrom, paths.TurnDir)
|
||||
state.carryFrom = ""
|
||||
}
|
||||
if err := writeFindingsFile(paths, state.findings); err != nil {
|
||||
return err
|
||||
}
|
||||
ledger := state.findings
|
||||
history := turn.RenderHistory(state.turns)
|
||||
memory := turn.RenderEssential(turn.Essential{
|
||||
Task: state.prompt,
|
||||
@@ -79,6 +89,7 @@ func (r *runner) prepareTurn(paths turn.Paths, state *runState, retryInput stage
|
||||
ChangedFiles: state.capturedList(),
|
||||
InputPath: paths.InputPath,
|
||||
HistoryPath: paths.HistoryPath,
|
||||
Findings: func(limit int) string { return findings.RenderMemory(ledger, limit) },
|
||||
})
|
||||
for _, file := range []struct{ path, content string }{
|
||||
{paths.InputPath, input},
|
||||
|
||||
Reference in New Issue
Block a user