package turn import ( "fmt" "strings" "unicode/utf8" ) // 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 // essentialOwnHandoffCap bounds a revisiting stage's own last handoff // (for example a reviewer's earlier must-fix findings it must confirm). 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. type Essential struct { // Task is the run prompt. Task string // StageKey is the stage about to run; it marks a revisit. StageKey string // Entries are the completed turns in order (the same slice history.md is // rendered from). Entries []MemoryEntry // ChangedFiles is the run's server-captured changed-path list. ChangedFiles []string // 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. 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 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 != "" { b.WriteString(" Read on demand only:") if e.InputPath != "" { fmt.Fprintf(&b, " %s (full task and previous stage output)", e.InputPath) } if e.HistoryPath != "" { if e.InputPath != "" { b.WriteString(";") } fmt.Fprintf(&b, " %s (every earlier turn in full)", e.HistoryPath) } b.WriteString(".") } b.WriteString("\n") task := strings.TrimSpace(demoteHeadings(strings.TrimSpace(e.Task))) if task == "" { task = "_(no task text)_" } 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) handoff, source := previousHandoff(previous.Output) if public := sortedUnique(previous.PublicFiles); len(public) > 0 { handoff += "\n\nAdded to public/: " + capLine(strings.Join(public, ", "), 2*essentialLineCap) } 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") } 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 } // HandoffSection returns the body of the first "handoff" heading (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 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 end := len(markdown) for i, line := range lines { if fence.open() { if fence.closes(line.text) { fence = fenceState{} } continue } if marker, ok := openingFence(line.text); ok { fence = marker continue } lvl, text, isHeading := atxHeading(line.text) if !isHeading { continue } if start < 0 { if strings.EqualFold(text, name) { start, level = line.next, lvl } continue } if lvl <= level { end = lines[i-1].next break } } if start < 0 { return "", false } section := strings.TrimSpace(markdown[start:end]) 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, limit int) string { if current == "" || limit < 256 { 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) 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 "" } func previousHandoff(output string) (string, string) { if section, ok := HandoffSection(output); ok { return strings.TrimSpace(demoteHeadings(section)), "" } body := strings.TrimSpace(demoteHeadings(output)) if body == "" { return "_(no output)_", "" } return body, "_(no `# handoff` section; showing the start of its output)_\n\n" } func renderLedger(entries []MemoryEntry, current string) string { if len(entries) == 0 { return "" } type latest struct { entry MemoryEntry order int } byStage := map[string]*latest{} order := []string{} for i, entry := range entries { if item, ok := byStage[entry.Stage]; ok { item.entry, item.order = entry, i continue } byStage[entry.Stage] = &latest{entry: entry, order: i} order = append(order, entry.Stage) } var b strings.Builder skipped := 0 if len(order) > essentialLedgerLines { skipped = len(order) - essentialLedgerLines order = order[skipped:] } if skipped > 0 { fmt.Fprintf(&b, "- … %d earlier stages in history.md\n", skipped) } for _, key := range order { item := byStage[key] line := fmt.Sprintf("%s · visit %d%s", oneLine(key), item.entry.Visit, outcomeSuffix(item.entry.Outcome)) if key == current { line += " (this stage's previous visit; detail in history.md)" } b.WriteString("- ") b.WriteString(capLine(line, essentialLineCap)) b.WriteString("\n") } fmt.Fprintf(&b, "\n%d turns completed.\n", len(entries)) return b.String() } func renderFiles(files []string) string { files = sortedUnique(files) if len(files) == 0 { return "" } var b strings.Builder shown := files if len(shown) > essentialFileLines { shown = shown[:essentialFileLines] } for _, name := range shown { b.WriteString("- ") b.WriteString(capLine(oneLine(name), essentialLineCap)) b.WriteString("\n") } if more := len(files) - len(shown); more > 0 { fmt.Fprintf(&b, "- … and %d more\n", more) } return b.String() } func outcomeSuffix(outcome string) string { if outcome == "" { return "" } return " · outcome " + oneLine(outcome) } func atxHeading(text string) (int, string, bool) { trimmed := strings.TrimLeft(text, " ") if len(text)-len(trimmed) > 3 { return 0, "", false } level := 0 for level < len(trimmed) && trimmed[level] == '#' { level++ } if level < 1 || level > 6 { return 0, "", false } rest := trimmed[level:] if rest != "" && rest[0] != ' ' && rest[0] != '\t' { return 0, "", false } return level, strings.TrimSpace(strings.TrimRight(strings.TrimSpace(rest), "#")), true } func oneLine(text string) string { return strings.Join(strings.Fields(text), " ") } func capLine(text string, limit int) string { if len(text) <= limit { return text } return cutAtRune(text, limit-len("…")) + "…" } func truncationNote(shown, total int, where string) string { return fmt.Sprintf("\n\n_[truncated: %d of %d bytes shown; full text in %s]_", shown, total, where) } // truncateWithNote returns text unchanged when it fits limit, otherwise its // head cut at a line (or rune) boundary followed by a pointer to the full text. func truncateWithNote(text string, limit int, where string) string { if len(text) <= limit { return text } if limit < 0 { limit = 0 } head := cutAtRune(text, limit) if i := strings.LastIndexByte(head, '\n'); i > limit/2 { head = head[:i] } head = strings.TrimRight(head, " \t\n") return head + truncationNote(len(head), len(text), where) } func cutAtRune(text string, limit int) string { if limit <= 0 { return "" } if len(text) <= limit { return text } for limit > 0 && !utf8.RuneStart(text[limit]) { limit-- } return text[:limit] }