Retries: tell stages why the last attempt failed; resume interrupted runs

- turn.RenderPreviousAttempt: bounded "# Previous attempt" section (attempt
  number, failing stage, bounded diagnostic, partial-edits note).
- In-stage retries (stage/model_run.go) append it instead of resending an
  identical prompt; run retries (resume and restart) add it to the first
  model visit's input.md, numbering attempts along the retry chain.
- --input-file retry overrides render only the override keys in input.md,
  labelled "# Operator correction" (the step row keeps the merged input).
- Essential memory (memory.md) inlines a revisiting stage's own last handoff,
  bounded, besides the previous stage's handoff.
- Interrupted runs can be retried: resume reruns the interrupted visit, or
  starts the next stage after the last completed visit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 00:22:45 +00:00
parent accb9970b6
commit ae4526d87c
9 changed files with 458 additions and 29 deletions
+111
View File
@@ -0,0 +1,111 @@
package server
import (
"context"
"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"
)
const threeStageModelSource = "# stage a\n\n```prompt\nDo A.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> b\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n\n# stage b\n\n```prompt\nDo B.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> c\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n\n# stage c\n\n```prompt\nDo C.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> #success\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n"
// TestRetryResumesAnInterruptedRunAfterItsLastCompletedStep proves a run the
// server stopped (interrupted) can be retried: it resumes after its last
// completed step without rerunning that prefix, whether the stop came during a
// visit (the interrupted visit runs again) or between visits (the next stage
// starts with the completed visit's handoff).
func TestRetryResumesAnInterruptedRunAfterItsLastCompletedStep(t *testing.T) {
for _, midVisit := range []bool{true, false} {
name := "between-visits"
if midVisit {
name = "mid-visit"
}
t.Run(name, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "interrupted.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if _, err := store.Submit(ctx, "resume", threeStageModelSource); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
d, err := store.Get(ctx, items[0].ID, 1)
if err != nil {
t.Fatal(err)
}
workspace := t.TempDir()
id, _, err := store.CreateRun(ctx, d, "interrupted-"+name, workspace, true, nil, map[string]any{"prompt": "task"})
if err != nil {
t.Fatal(err)
}
if err := store.BeginStep(ctx, id, 1, "a", map[string]any{"prompt": "task"}); err != nil {
t.Fatal(err)
}
if err := store.FinishStep(ctx, id, protocol.RunStep{Sequence: 1, Stage: "a", Status: "completed", Outcome: "success", Target: "b", Output: map[string]any{"handoff": "from-a"}}); err != nil {
t.Fatal(err)
}
if midVisit {
if err := store.BeginStep(ctx, id, 2, "b", map[string]any{"handoff": "from-a"}); err != nil {
t.Fatal(err)
}
}
if err := store.RecoverRuns(ctx); err != nil {
t.Fatal(err)
}
source, err := store.GetRun(ctx, id)
if err != nil || source.Status != "interrupted" {
t.Fatalf("source run was not interrupted: %+v %v", source, err)
}
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
calls := map[string]int{}
r.execute = func(_ context.Context, def stage.Definition, input stage.Values) (stage.Result, error) {
calls[def.Key]++
switch def.Key {
case "b":
if input["handoff"] != "from-a" {
t.Errorf("resumed stage lost the completed handoff: %#v", input)
}
data, err := os.ReadFile(def.Turn.Input)
if err != nil {
t.Fatalf("read input.md: %v", err)
}
if !strings.Contains(string(data), "# Previous attempt") || !strings.Contains(string(data), "This is attempt 2.") {
t.Errorf("resumed stage was not told about the previous attempt:\n%s", data)
}
return stage.Result{Outcome: "success", Output: stage.Values{"handoff": "from-b"}}, nil
case "c":
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
t.Errorf("unexpected stage %q", def.Key)
return stage.Result{}, nil
}
retried, err := r.retry(protocol.Message{RunID: id, RequestKey: "resume-" + name})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
retried, err = store.GetRun(ctx, retried.ID)
if err != nil || retried.Status != "succeeded" || retried.RetrySource != id {
t.Fatalf("interrupted run did not resume to success: %+v %v", retried, err)
}
if calls["a"] != 0 || calls["b"] != 1 || calls["c"] != 1 {
t.Fatalf("resume reran the completed prefix or skipped work: %v", calls)
}
if len(retried.Steps) == 0 || retried.Steps[0].Stage != "b" || retried.Steps[0].Sequence != 2 {
t.Fatalf("resume started at the wrong step: %+v", retried.Steps)
}
})
}
}
+14
View File
@@ -356,6 +356,20 @@ func TestRetryResumeReusesPrefixHandoffAndReplaysRequestAfterReopen(t *testing.T
if !strings.Contains(string(data), want) {
t.Errorf("retry input.md missing override %q:\n%s", want, data)
}
// Only the override keys are shown, labelled as the operator's
// correction; the merged input (handoff from A) is not reprinted.
text := string(data)
section := text[strings.Index(text, "# Operator correction"):]
if !strings.Contains(text, "# Operator correction") || strings.Contains(section, "from-a") || strings.Contains(text, "# Retry input") {
t.Errorf("retry input.md did not render only the operator correction:\n%s", data)
}
// The retried stage learns why the source attempt failed.
wantAttempt := fmt.Sprintf("This is attempt %d.", bCalls)
for _, want := range []string{"# Previous attempt", wantAttempt, "failed in stage b", "deliberate failure", "Partial edits"} {
if !strings.Contains(text, want) {
t.Errorf("retry input.md missing %q:\n%s", want, data)
}
}
}
if bCalls <= 2 {
return stage.Result{}, fmt.Errorf("deliberate failure")
+97 -11
View File
@@ -662,8 +662,9 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.
if err != nil {
return retryCheckpoint{}, err
}
if source.Status != "failed" || source.FinishedAt == "" {
return retryCheckpoint{}, fmt.Errorf("retry source %d is not a terminal failed run", sourceID)
interrupted := source.Status == "interrupted"
if (source.Status != "failed" && !interrupted) || source.FinishedAt == "" {
return retryCheckpoint{}, fmt.Errorf("retry source %d is not a terminal failed or interrupted run", sourceID)
}
if source.PipelineID != pinned.ID {
return retryCheckpoint{}, fmt.Errorf("retry source %d belongs to a different pipeline", sourceID)
@@ -672,6 +673,28 @@ 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 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
// last recorded visit completed and routed to its next stage). Either
// way the run resumes after its last completed step: the interrupted
// visit runs again, or the next stage starts with the handoff the
// completed visit produced.
switch failed.Status {
case "interrupted":
failed.Target = protocol.FailureEnd
case "completed":
if failed.Target == "" || failed.Target == protocol.SuccessEnd || failed.Target == protocol.FailureEnd {
return retryCheckpoint{}, fmt.Errorf("retry source %d has no unfinished stage to resume; use --mode=restart", sourceID)
}
failed = protocol.RunStep{Sequence: failed.Sequence + 1, Stage: failed.Target, Status: "interrupted", Target: protocol.FailureEnd, Input: failed.Output}
if failed.Input == nil {
failed.Input = map[string]any{}
}
default:
return retryCheckpoint{}, fmt.Errorf("retry source %d has no safe interrupted-stage checkpoint; use --mode=restart", sourceID)
}
}
if selectedStage != "" {
failed = protocol.RunStep{}
visits := 0
@@ -705,7 +728,7 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.
return retryCheckpoint{}, fmt.Errorf("retry stage %q has no visit %d", selectedStage, selectedVisit)
}
}
if (failed.Status != "completed" && failed.Status != "failed") || (selectedStage == "" && failed.Target != protocol.FailureEnd) {
if (failed.Status != "completed" && failed.Status != "failed" && !(interrupted && failed.Status == "interrupted")) || (selectedStage == "" && failed.Target != protocol.FailureEnd) {
return retryCheckpoint{}, fmt.Errorf("retry source %d has no safe failed-stage checkpoint", sourceID)
}
var handoff map[string]any
@@ -813,8 +836,10 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) {
if original.Executing {
return nil, fmt.Errorf("run %d is still executing; wait for it to stop completely before retrying", original.ID)
}
if original.Status != "failed" || original.FinishedAt == "" {
return nil, fmt.Errorf("only failed runs can be retried (run %d is %s)", original.ID, original.Status)
// An interrupted run (the server stopped mid-run) resumes after its last
// completed step, like a failed run resumes its failed stage.
if (original.Status != "failed" && original.Status != "interrupted") || original.FinishedAt == "" {
return nil, fmt.Errorf("only failed or interrupted runs can be retried (run %d is %s)", original.ID, original.Status)
}
if request.RequestKey == "" {
return nil, fmt.Errorf("retry requires an idempotency request key")
@@ -998,6 +1023,7 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
return
}
state := rebuildRetryState(source, checkpoint.failed, storedHandoff)
state.previousAttempt = r.previousAttemptSection(ctx, source, d.Graph, state.key)
if override, ok := storedHandoff["override"].(map[string]any); ok {
state.retryOverride = stage.Values(override)
}
@@ -1019,9 +1045,65 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
input := stage.Values(request.Input)
state := newRunState(d.Graph.Stages[0].Key, input)
state.memory["input"] = memoryValue{output: original}
if request.RetrySource > 0 {
// A restart from entry still tells its first model visit why the
// source run failed.
if source, err := r.store.GetRun(ctx, request.RetrySource); err == nil {
state.previousAttempt = r.previousAttemptSection(ctx, source, d.Graph, state.key)
}
}
r.runLoop(ctx, id, d.Graph, d.Name, workspace, request, state)
}
// maxRetryChain bounds the walk that numbers a retry attempt.
const maxRetryChain = 50
// previousAttemptSection renders the bounded "# Previous attempt" section for
// a retried run whose first visit is the model stage firstStage: the attempt
// number (counted along the retry chain), the stage the source run stopped in
// and its diagnostic. A first visit that is not a model stage gets nothing, so
// the note never lands on an unrelated later stage.
func (r *runner) previousAttemptSection(ctx context.Context, source *protocol.RunDetail, graph protocol.Graph, firstStage string) string {
if source == nil {
return ""
}
model := false
for _, declared := range graph.Stages {
if declared.Key == firstStage {
model = stage.EffectiveType(declared.Type) == stage.ModelType
}
}
if !model {
return ""
}
parentOf := func(d *protocol.RunDetail) int64 {
if d.RetryOf > 0 {
return d.RetryOf
}
return d.RetrySource
}
attempt := 2
for previous := parentOf(source); previous > 0 && attempt < maxRetryChain; attempt++ {
ancestor, err := r.store.GetRun(ctx, previous)
if err != nil || ancestor == nil {
break
}
previous = parentOf(ancestor)
}
failedStage, diagnostic := source.CurrentStage, ""
if n := len(source.Steps); n > 0 {
last := source.Steps[n-1]
failedStage, diagnostic = last.Stage, strings.TrimSpace(last.Diagnostic)
}
if diagnostic == "" {
diagnostic = strings.TrimSpace(source.Diagnostic)
}
if diagnostic == "" {
diagnostic = strings.TrimSpace(source.FailureReason)
}
return turn.RenderPreviousAttempt(turn.PreviousAttempt{Attempt: attempt, Stage: failedStage, Diagnostic: diagnostic, Run: source.ID})
}
// terminalFinish classifies a stage's resolved target. A terminal key yields the
// run's final status, outcome and diagnostic; an empty target means the stage
// named an undeclared outcome; any other value is a stage key and is not
@@ -1098,7 +1180,10 @@ type runState struct {
// retryOverride is applied once, after the selected stage's memory bindings
// have been resolved. It is intentionally not part of run input or memory.
retryOverride stage.Values
priorBudgets map[string]stage.BudgetSnapshot
// previousAttempt is the rendered "# Previous attempt" section a retried
// run's first model visit receives; prepareTurn consumes it.
previousAttempt string
priorBudgets map[string]stage.BudgetSnapshot
// adopt names the visit to re-adopt from a previous server process instead
// of starting it; it is consumed by the loop's first iteration.
adopt *adoptedVisit
@@ -1779,11 +1864,12 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
finish("failed", "error", copyErr.Error())
return
}
// Keep the merged values for this visit's input.md: the model reads
// files, not the persisted step row, so the override must be visible
// there. A selected-stage override belongs only to this invocation,
// not to a later visit reached through the stage graph.
retryInput = input
// The step row persists the merged input; input.md shows only the
// operator's override keys: the model reads files, not the step row,
// so the correction must be visible there, without re-printing the
// whole input. A selected-stage override belongs only to this
// invocation, not to a later visit reached through the stage graph.
retryInput = state.retryOverride
state.retryOverride = nil
}
if adopted == nil {
+29 -17
View File
@@ -52,15 +52,25 @@ func stageTurnPaths(paths turn.Paths) stage.TurnPaths {
// completed turn in full) before the visit starts. A failure here is a run failure: the file
// protocol is the stage contract, not best-effort evidence.
//
// retryInput is the complete merged input for a selected-stage retry and nil for
// an ordinary visit. A retry override is persisted on the step, but the model
// reads input.md rather than the step row, so the same values must be written
// into the file or the operator's correction is invisible to the model.
// retryInput is the operator's override for a selected-stage retry (only the
// keys it sets) and nil for an ordinary visit. The merged input is persisted on
// the step, but the model reads input.md rather than the step row, so the
// correction must be written into the file or it is invisible to the model.
// A retried run's first visit also gets a bounded "# Previous attempt" section
// saying why the source run failed; it is consumed here so later visits do not
// repeat it.
func (r *runner) prepareTurn(paths turn.Paths, state *runState, retryInput stage.Values) error {
if err := paths.Ensure(); err != nil {
return err
}
input := turnInputWithRetry(state.turnInput(), retryInput)
if state.previousAttempt != "" {
if !strings.HasSuffix(input, "\n") {
input += "\n"
}
input += "\n" + state.previousAttempt
state.previousAttempt = ""
}
history := turn.RenderHistory(state.turns)
memory := turn.RenderEssential(turn.Essential{
Task: state.prompt,
@@ -82,24 +92,26 @@ func (r *runner) prepareTurn(paths turn.Paths, state *runState, retryInput stage
return nil
}
// turnInputWithRetry appends the merged retry input to the ordinary turn input.
// It is rendered as a fenced JSON object because the values are operator data,
// not prose; encoding/json sorts map keys so the file is deterministic.
func turnInputWithRetry(base string, retryInput stage.Values) string {
if len(retryInput) == 0 {
// turnInputWithRetry appends the operator's retry override to the ordinary turn
// input as an "Operator correction": only the keys the operator set, not the
// whole merged input the stage already has. It is rendered as a fenced JSON
// object because the values are operator data, not prose; encoding/json sorts
// map keys so the file is deterministic.
func turnInputWithRetry(base string, override stage.Values) string {
if len(override) == 0 {
return base
}
encoded, err := json.MarshalIndent(retryInput, "", " ")
if err != nil {
// A retry input that cannot be rendered is still shown as a visible
// section; the stage can choose its error outcome rather than silently
// receiving a correction it cannot see.
return base + "\n\n# Retry input\n\nThe retry input could not be rendered.\n"
}
if !strings.HasSuffix(base, "\n") {
base += "\n"
}
return base + "\n# Retry input\n\nThis retry was given this complete input:\n\n```json\n" + string(encoded) + "\n```\n"
encoded, err := json.MarshalIndent(override, "", " ")
if err != nil {
// A correction that cannot be rendered is still shown as a visible
// section; the stage can choose its error outcome rather than silently
// receiving a correction it cannot see.
return base + "\n# Operator correction\n\nThe operator's retry correction could not be rendered.\n"
}
return base + "\n# Operator correction\n\nThe operator retried this stage with these corrected input values; they override the earlier ones:\n\n```json\n" + string(encoded) + "\n```\n"
}
// turnInput is the run prompt on the first visit; later visits carry the run
+8 -1
View File
@@ -7,6 +7,7 @@ import (
"time"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/turn"
)
func (m ModelStage) Run(ctx context.Context, def Definition, input Values) (Result, error) {
@@ -71,7 +72,13 @@ func (m ModelStage) Run(ctx context.Context, def Definition, input Values) (Resu
attemptCtx, cancel := context.WithTimeoutCause(ctx, spec.Config.Timeout, &stageTimeoutCause{timeout: spec.Config.Timeout})
// A completed turn without a valid outcome gets one in-session follow-up
// asking only for the outcome, rather than a full retry of its work.
text, generateErr := client.Generate(withOutputRepair(attemptCtx, outcomesFor(def.Edges)), spec.Config, prompt)
attemptPrompt := prompt
if attempt > 0 && err != nil {
// An in-stage retry says why the last attempt failed rather than
// resending an identical prompt that invites the same failure.
attemptPrompt = prompt + "\n\n" + turn.RenderPreviousAttempt(turn.PreviousAttempt{Attempt: attempt + 1, Stage: def.Key, Diagnostic: err.Error()})
}
text, generateErr := client.Generate(withOutputRepair(attemptCtx, outcomesFor(def.Edges)), spec.Config, attemptPrompt)
if generateErr == nil && attemptCtx.Err() != nil {
generateErr = attemptCtx.Err()
}
+48
View File
@@ -0,0 +1,48 @@
package stage
import (
"context"
"strings"
"testing"
)
type retryableTestError struct{ text string }
func (e retryableTestError) Error() string { return e.text }
func (e retryableTestError) Retryable() bool { return true }
// TestInStageRetryTellsTheModelWhyTheLastAttemptFailed proves an in-stage
// retry does not resend an identical prompt: the second attempt carries a
// bounded "# Previous attempt" section with the attempt number, the stage and
// the last failure, while the first attempt is unchanged.
func TestInStageRetryTellsTheModelWhyTheLastAttemptFailed(t *testing.T) {
def := turnDefinition(t)
def.Configs["retries"] = "1"
prompts := []string{}
client := generatorFunc(func(_ context.Context, _ ModelConfig, prompt string) (string, error) {
prompts = append(prompts, prompt)
if len(prompts) == 1 {
return "", retryableTestError{"provider overloaded: " + strings.Repeat("x", 5000)}
}
return "# outcome\nsuccess\n\n# handoff\n\ndone\n", nil
})
result, err := (ModelStage{Client: client}).Run(context.Background(), def, Values{"prompt": "task"})
if err != nil || result.Outcome != "success" || len(prompts) != 2 {
t.Fatalf("retry did not succeed: %+v %v prompts=%d", result, err, len(prompts))
}
if strings.Contains(prompts[0], "# Previous attempt") {
t.Fatalf("first attempt carried a previous-attempt section:\n%s", prompts[0])
}
second := prompts[1]
if !strings.HasPrefix(second, prompts[0]) {
t.Fatal("retry prompt does not extend the original prompt")
}
for _, want := range []string{"# Previous attempt", "attempt 2 of stage " + def.Key, "provider overloaded", "Partial edits", "[truncated]"} {
if !strings.Contains(second, want) {
t.Fatalf("retry prompt missing %q:\n%s", want, second[len(prompts[0]):])
}
}
if extra := len(second) - len(prompts[0]); extra > 2600 {
t.Fatalf("previous-attempt section is unbounded: %d bytes", extra)
}
}
+57
View File
@@ -0,0 +1,57 @@
package turn
import (
"fmt"
"strings"
)
// PreviousAttemptCap bounds the diagnostic carried into a "# Previous attempt"
// section. A failure's head usually names the cause, so the head is kept.
const PreviousAttemptCap = 2000
// PreviousAttempt describes the attempt that failed before this one: a run
// retry (the source run's failing stage) or a stage's own in-stage retry.
type PreviousAttempt struct {
// Attempt is the 1-based number of the attempt that is about to run.
Attempt int
// Stage is the stage the previous attempt failed in.
Stage string
// Diagnostic is why it failed; it is bounded when rendered.
Diagnostic string
// Run is the failed source run for a run retry; 0 for an in-stage retry.
Run int64
}
// RenderPreviousAttempt renders a bounded "# Previous attempt" section that
// tells a retried stage why the last attempt failed, so it does not repeat the
// same mistake, and that partial edits from it may remain in the worktree.
func RenderPreviousAttempt(p PreviousAttempt) string {
var b strings.Builder
b.WriteString("# Previous attempt\n\n")
attempt := p.Attempt
if attempt < 2 {
attempt = 2
}
stageName := oneLine(p.Stage)
if stageName == "" {
stageName = "unknown"
}
if p.Run > 0 {
fmt.Fprintf(&b, "This is attempt %d. The previous attempt (run %d) failed in stage %s.", attempt, p.Run, capLine(stageName, essentialLineCap))
} else {
fmt.Fprintf(&b, "This is attempt %d of stage %s. The previous attempt failed.", attempt, capLine(stageName, essentialLineCap))
}
b.WriteString(" Partial edits from it may still be in the worktree; check them before redoing work.\n")
detail := strings.TrimSpace(p.Diagnostic)
if detail == "" {
b.WriteString("\nNo diagnostic was recorded.\n")
return b.String()
}
if len(detail) > PreviousAttemptCap {
detail = strings.ToValidUTF8(cutAtRune(detail, PreviousAttemptCap), "") + "\n[truncated]"
}
b.WriteString("\nDiagnostic:\n\n~~~\n")
b.WriteString(strings.ReplaceAll(detail, "~~~", "~ ~ ~"))
b.WriteString("\n~~~\n")
return b.String()
}
+66
View File
@@ -0,0 +1,66 @@
package turn
import (
"strings"
"testing"
)
func TestRenderPreviousAttemptIsBoundedAndNamesTheFailure(t *testing.T) {
text := RenderPreviousAttempt(PreviousAttempt{Attempt: 3, Stage: "land", Run: 42, Diagnostic: "checks failed: go test ./...\n~~~\n" + strings.Repeat("y", 9000)})
for _, want := range []string{"# Previous attempt", "attempt 3", "run 42", "stage land", "checks failed", "Partial edits", "[truncated]"} {
if !strings.Contains(text, want) {
t.Fatalf("missing %q:\n%s", want, text)
}
}
if len(text) > PreviousAttemptCap+500 {
t.Fatalf("section is %d bytes", len(text))
}
// A diagnostic cannot close the fence early.
if strings.Count(text, "~~~") != 2 {
t.Fatalf("diagnostic broke the fence:\n%s", text)
}
empty := RenderPreviousAttempt(PreviousAttempt{Stage: "plan"})
if !strings.Contains(empty, "No diagnostic was recorded.") || !strings.Contains(empty, "attempt 2 of stage plan") {
t.Fatalf("empty diagnostic rendering:\n%s", empty)
}
}
// TestEssentialMemoryRevisitShowsOwnPreviousHandoff proves a stage that runs
// again (a reviewer after the implementer fixed its findings) sees its own last
// handoff, bounded, besides the immediately previous stage's handoff.
func TestEssentialMemoryRevisitShowsOwnPreviousHandoff(t *testing.T) {
entries := feedbackLoopEntries()
entries = append(entries, MemoryEntry{Stage: "code", Visit: 2, Outcome: "success", Output: "# handoff\n\nFixed the lock leak and added the eviction test.\n"})
memory := RenderEssential(Essential{Task: "Add a cache.", StageKey: "review", Entries: entries, InputPath: "in.md", HistoryPath: "hist.md"})
if len(memory) > EssentialCap {
t.Fatalf("essential memory is %d bytes, over the cap", len(memory))
}
for _, want := range []string{
"## Previous stage: code · visit 2",
"Fixed the lock leak",
"## This stage's previous visit: review · visit 1 · outcome changes_requested",
"cache.go:42 leaks the lock on the error path.",
} {
if !strings.Contains(memory, want) {
t.Fatalf("memory missing %q:\n%s", want, memory)
}
}
if strings.Contains(memory, "Long preamble.") {
t.Fatalf("own handoff carried non-handoff text:\n%s", memory)
}
// Long own handoffs are bounded with a pointer to history.md.
entries[2].Output = "# handoff\n\n" + paragraph("finding", 5000)
memory = RenderEssential(Essential{Task: "Add a cache.", StageKey: "review", Entries: entries, InputPath: "in.md", HistoryPath: "hist.md"})
if len(memory) > EssentialCap || !strings.Contains(memory, "full text in history.md") {
t.Fatalf("own handoff not bounded (%d bytes):\n%s", len(memory), memory)
}
// No own section on a first visit or when the previous turn is this stage.
for _, key := range []string{"land", "code"} {
memory = RenderEssential(Essential{Task: "Add a cache.", StageKey: key, Entries: entries})
if strings.Contains(memory, "This stage's previous visit") {
t.Fatalf("%s got an own-handoff section:\n%s", key, memory)
}
}
}
+28
View File
@@ -19,6 +19,9 @@ const (
// essentialHandoffMin is the least room a previous stage's handoff gets
// when the task also needs more than half of the remaining budget.
essentialHandoffMin = 1024
// essentialOwnHandoffCap bounds a revisiting stage's own last handoff
// (for example a reviewer's earlier must-fix findings it must confirm).
essentialOwnHandoffCap = 768
)
// Essential is everything RenderEssential needs for one visit's memory.md.
@@ -63,6 +66,7 @@ func RenderEssential(e Essential) string {
fixed.WriteString("\n")
var tail strings.Builder
tail.WriteString(renderOwnHandoff(e.Entries, e.StageKey))
if ledger := renderLedger(e.Entries, e.StageKey); ledger != "" {
tail.WriteString("\n## Stage ledger\n\n")
tail.WriteString(ledger)
@@ -180,6 +184,30 @@ func HandoffSection(markdown string) (string, bool) {
return section, section != ""
}
// renderOwnHandoff returns a bounded section with the stage's own handoff from
// its latest earlier visit, so a revisiting stage (a reviewer confirming its
// previous must-fix findings) sees what it said last time. It is empty on a
// first visit and when that visit is the immediately previous turn, which the
// "Previous stage" section already shows.
func renderOwnHandoff(entries []MemoryEntry, current string) string {
if current == "" {
return ""
}
for i := len(entries) - 1; i >= 0; i-- {
if entries[i].Stage != current {
continue
}
if i == len(entries)-1 {
return ""
}
own := entries[i]
body, source := previousHandoff(own.Output)
title := capLine(fmt.Sprintf("%s · visit %d%s", oneLine(own.Stage), own.Visit, outcomeSuffix(own.Outcome)), 2*essentialLineCap)
return "\n## This stage's previous visit: " + title + "\n\n" + source + truncateWithNote(body, essentialOwnHandoffCap, "history.md") + "\n"
}
return ""
}
func previousHandoff(output string) (string, string) {
if section, ok := HandoffSection(output); ok {
return strings.TrimSpace(demoteHeadings(section)), ""