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:
2026-12-03 14:35:54 +00:00
66 changed files with 3565 additions and 148 deletions
+93 -87
View File
@@ -6,22 +6,32 @@ import (
"unicode/utf8"
)
// EssentialCap is the hard byte cap on a visit's memory.md (essential memory).
// It is small on purpose: the file is inlined into every model call of the
// visit, so its size is paid once per call. Everything else stays on disk in
// history.md and input.md, read only on demand.
const EssentialCap = 4096
// EssentialCap is the byte budget of a visit's memory.md (essential memory).
// The file is inlined into every model call of the visit, so it stays bounded;
// everything else stays on disk in history.md and input.md, read on demand.
//
// The run task is never truncated (up to EssentialTaskMax): a task larger than
// the budget grows the file to the task plus essentialMinRest for the other
// sections, so EssentialMax is the absolute bound.
const (
EssentialCap = 20 << 10
EssentialTaskMax = 64 << 10
essentialMinRest = 4 << 10
EssentialMax = EssentialTaskMax + essentialMinRest + 1024
)
const (
essentialLedgerLines = 10
essentialFileLines = 8
essentialLineCap = 100
// 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
essentialOwnHandoffCap = 4 << 10
// essentialFindingsCap bounds the findings ledger section.
essentialFindingsCap = 8 << 10
// essentialReserve keeps room for the short trailing sections when the
// previous handoff is long.
essentialReserve = 1536
)
// Essential is everything RenderEssential needs for one visit's memory.md.
@@ -38,108 +48,94 @@ type Essential struct {
// InputPath and HistoryPath are named as the on-demand detail.
InputPath string
HistoryPath string
// Findings renders the run's findings ledger section within limit bytes
// (empty when there is no ledger). Nil means no section.
Findings func(limit int) string
}
// RenderEssential renders a visit's essential memory: the task, the previous
// stage's handoff, a one-line-per-stage outcome ledger and the changed files.
// The result never exceeds EssentialCap bytes. The previous stage's handoff is
// its "# handoff" section when it wrote one, otherwise the head of its output;
// either is truncated with a pointer to the full text, so the file stays useful
// whether or not a model followed the handoff convention.
// RenderEssential renders a visit's essential memory. Sections in priority
// order: the task (never truncated), the previous stage's handoff, the open
// findings ledger, this stage's own previous handoff, a one-line-per-stage
// outcome ledger and the changed files. Lower-priority sections shrink or are
// dropped first. The result fits EssentialCap unless the task alone needs
// more (see EssentialMax). The previous stage's handoff is its "# handoff"
// section when it wrote one, otherwise the head of its output; either is
// truncated with a pointer to the full text.
func RenderEssential(e Essential) string {
var fixed strings.Builder
fixed.WriteString("# Essential memory\n\n")
fixed.WriteString("Short handoff for this visit; enough for most work.")
var b strings.Builder
b.WriteString("# Essential memory\n\n")
b.WriteString("Short handoff for this visit; enough for most work.")
if e.InputPath != "" || e.HistoryPath != "" {
fixed.WriteString(" Read on demand only:")
b.WriteString(" Read on demand only:")
if e.InputPath != "" {
fmt.Fprintf(&fixed, " %s (full task and previous stage output)", e.InputPath)
fmt.Fprintf(&b, " %s (full task and previous stage output)", e.InputPath)
}
if e.HistoryPath != "" {
if e.InputPath != "" {
fixed.WriteString(";")
b.WriteString(";")
}
fmt.Fprintf(&fixed, " %s (every earlier turn in full)", e.HistoryPath)
fmt.Fprintf(&b, " %s (every earlier turn in full)", e.HistoryPath)
}
fixed.WriteString(".")
b.WriteString(".")
}
fixed.WriteString("\n")
b.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)
}
if files := renderFiles(e.ChangedFiles); files != "" {
tail.WriteString("\n## Changed files (server-captured)\n\n")
tail.WriteString(files)
}
taskHeading := "\n## Task\n\n"
task := strings.TrimSpace(demoteHeadings(strings.TrimSpace(e.Task)))
if task == "" {
task = "_(no task text)_"
}
var handoffHeading, handoff string
if len(task) > EssentialTaskMax {
task = truncateWithNote(task, EssentialTaskMax, "input.md")
}
b.WriteString("\n## Task\n\n")
b.WriteString(task)
b.WriteString("\n")
limit := EssentialCap
if need := b.Len() + essentialMinRest; need > limit {
limit = need
}
room := func() int { return limit - b.Len() }
if n := len(e.Entries); n > 0 {
previous := e.Entries[n-1]
title := capLine(fmt.Sprintf("%s · visit %d%s", oneLine(previous.Stage), previous.Visit, outcomeSuffix(previous.Outcome)), 2*essentialLineCap)
handoffHeading = "\n## Previous stage: " + title + "\n\n"
var source string
handoff, source = previousHandoff(previous.Output)
handoffHeading += source
handoff, source := previousHandoff(previous.Output)
if public := sortedUnique(previous.PublicFiles); len(public) > 0 {
handoff += "\n\nAdded to public/: " + capLine(strings.Join(public, ", "), 2*essentialLineCap)
}
}
// Budget what is left after the fixed parts between the task and the
// handoff. Unused room on either side flows to the other.
reserve := 2 * len(truncationNote(EssentialCap, EssentialCap, "input.md"))
budget := EssentialCap - fixed.Len() - tail.Len() - len(taskHeading) - len(handoffHeading) - 2 - reserve
if budget < 0 {
budget = 0
}
handoffBudget, taskBudget := 0, budget
if handoffHeading != "" {
half := budget / 2
if half < essentialHandoffMin {
half = min(essentialHandoffMin, budget)
}
switch {
case len(task) <= budget-half:
handoffBudget = budget - len(task)
case len(handoff) <= half:
handoffBudget = len(handoff)
default:
handoffBudget = half
}
taskBudget = budget - min(handoffBudget, len(handoff))
}
var b strings.Builder
b.WriteString(fixed.String())
b.WriteString(taskHeading)
b.WriteString(truncateWithNote(task, taskBudget, "input.md"))
b.WriteString("\n")
if handoffHeading != "" {
b.WriteString(handoffHeading)
b.WriteString(truncateWithNote(handoff, handoffBudget, "input.md"))
heading := "\n## Previous stage: " + title + "\n\n" + source
budget := room() - len(heading) - 1 - essentialReserve - len(truncationNote(EssentialMax, EssentialMax, "input.md"))
b.WriteString(heading)
b.WriteString(truncateWithNote(handoff, max(budget, 256), "input.md"))
b.WriteString("\n")
} else {
b.WriteString("\nThis is the first stage of the run; there is no earlier turn.\n")
}
b.WriteString(tail.String())
out := b.String()
if len(out) > EssentialCap {
// Pathological input (very long stage keys or paths); never exceed the
// cap even if the section budgets could not absorb it.
out = truncateWithNote(out, EssentialCap-len(truncationNote(len(out), len(out), "history.md")), "history.md") + "\n"
if len(out) > EssentialCap {
out = cutAtRune(out, EssentialCap)
if e.Findings != nil {
if section := e.Findings(min(essentialFindingsCap, room()-essentialReserve/2)); section != "" && len(section) <= room() {
b.WriteString(section)
}
}
if own := renderOwnHandoff(e.Entries, e.StageKey, min(essentialOwnHandoffCap, room()-essentialReserve/2)); own != "" && len(own) <= room() {
b.WriteString(own)
}
if ledger := renderLedger(e.Entries, e.StageKey); ledger != "" {
if section := "\n## Stage ledger\n\n" + ledger; len(section) <= room() {
b.WriteString(section)
}
}
if files := renderFiles(e.ChangedFiles); files != "" {
if section := "\n## Changed files (server-captured)\n\n" + files; len(section) <= room() {
b.WriteString(section)
}
}
out := b.String()
if len(out) > EssentialMax {
// Pathological input; never exceed the absolute bound.
out = cutAtRune(out, EssentialMax)
}
return out
}
@@ -147,6 +143,14 @@ func RenderEssential(e Essential) string {
// level, outside fenced code) up to the next heading of the same or a higher
// level, trimmed. ok is false when there is no such heading or it is empty.
func HandoffSection(markdown string) (string, bool) {
return Section(markdown, "handoff")
}
// Section returns the body of the first heading named name (case-insensitive,
// any ATX level, outside fenced code) up to the next heading of the same or a
// higher level, trimmed. ok is false when there is no such heading or it is
// empty.
func Section(markdown, name string) (string, bool) {
lines := markdownLines(markdown)
var fence fenceState
start, level := -1, 0
@@ -167,7 +171,7 @@ func HandoffSection(markdown string) (string, bool) {
continue
}
if start < 0 {
if strings.EqualFold(text, "handoff") {
if strings.EqualFold(text, name) {
start, level = line.next, lvl
}
continue
@@ -189,8 +193,8 @@ func HandoffSection(markdown string) (string, bool) {
// 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 == "" {
func renderOwnHandoff(entries []MemoryEntry, current string, limit int) string {
if current == "" || limit < 256 {
return ""
}
for i := len(entries) - 1; i >= 0; i-- {
@@ -203,7 +207,9 @@ func renderOwnHandoff(entries []MemoryEntry, current string) string {
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"
heading := "\n## This stage's previous visit: " + title + "\n\n" + source
budget := limit - len(heading) - 1 - len(truncationNote(EssentialMax, EssentialMax, "history.md"))
return heading + truncateWithNote(body, max(budget, 0), "history.md") + "\n"
}
return ""
}
+33 -1
View File
@@ -103,7 +103,7 @@ func TestEssentialMemoryCapsEveryPart(t *testing.T) {
for i := range 200 {
files = append(files, fmt.Sprintf("%03d/%s", i, long))
}
memory := RenderEssential(Essential{Task: paragraph("task", 50000), StageKey: "next", Entries: entries, ChangedFiles: files, InputPath: "/in.md", HistoryPath: "/history.md"})
memory := RenderEssential(Essential{Task: paragraph("task", 5000), StageKey: "next", Entries: entries, ChangedFiles: files, InputPath: "/in.md", HistoryPath: "/history.md"})
if len(memory) > EssentialCap {
t.Fatalf("essential memory is %d bytes, over the %d cap", len(memory), EssentialCap)
}
@@ -114,6 +114,38 @@ func TestEssentialMemoryCapsEveryPart(t *testing.T) {
}
}
// TestEssentialMemoryNeverTruncatesTheTask proves a task larger than the
// budget is kept whole and the other sections share a bounded remainder, with
// the previous handoff and the findings ledger ahead of the outcome ledger.
func TestEssentialMemoryNeverTruncatesTheTask(t *testing.T) {
task := paragraph("task", 30000) + "THE END OF THE TASK"
entries := []MemoryEntry{
{Stage: "implement", Visit: 1, Outcome: "success", Output: "# handoff\n\n" + paragraph("handoff", 9000)},
{Stage: "review", Visit: 1, Outcome: "rejected", Output: "# handoff\n\nReview handoff: fix F1.\n"},
}
findings := func(limit int) string {
return "\n## Findings ledger (runner-owned)\n\n- F1 · important · introduced — leak\n"
}
memory := RenderEssential(Essential{Task: task, StageKey: "implement", Entries: entries, Findings: findings, InputPath: "/in.md", HistoryPath: "/history.md"})
if !strings.Contains(memory, "THE END OF THE TASK") || strings.Contains(memory[:strings.Index(memory, "THE END")], "_[truncated") {
t.Fatalf("task was truncated")
}
if len(memory) > len(task)+essentialMinRest+512 || len(memory) > EssentialMax {
t.Fatalf("memory %d bytes is not bounded by the task (%d) plus the minimum rest", len(memory), len(task))
}
handoff, ledger, own := strings.Index(memory, "Review handoff: fix F1."), strings.Index(memory, "## Findings ledger"), strings.Index(memory, "## This stage's previous visit")
if handoff < 0 || ledger < handoff {
t.Fatalf("handoff and findings missing or out of order:\n%s", memory[len(task)-200:])
}
if own >= 0 && own < ledger {
t.Fatalf("own handoff ahead of the findings ledger")
}
small := RenderEssential(Essential{Task: "Small task.", StageKey: "implement", Entries: entries, Findings: findings})
if len(small) > EssentialCap || !strings.Contains(small, "## Stage ledger") || !strings.Contains(small, "handoff: detail") {
t.Fatalf("small-task memory (%d bytes):\n%s", len(small), small)
}
}
func TestEssentialMemoryFirstVisit(t *testing.T) {
memory := RenderEssential(Essential{Task: "Do it.", StageKey: "plan", InputPath: "in.md", HistoryPath: "hist.md"})
for _, want := range []string{"## Task\n\nDo it.", "first stage of the run"} {