turn: keep turn headings structural in memory

Turn bodies were embedded verbatim, so a body's own ## headings looked like
sibling turns and could even duplicate the system's "Files added to public/"
line. Body headings are now demoted two levels (capped at H6) outside fences;
fenced code is untouched.
This commit is contained in:
2026-10-19 23:35:18 +01:00
parent 0219173327
commit 00252da8f8
3 changed files with 76 additions and 10 deletions
+59 -4
View File
@@ -26,9 +26,12 @@ type MemoryEntry struct {
PublicFiles []string
}
// RenderMemory renders completed turns in the order supplied. Each turn's output
// is embedded verbatim; the file list is system-written from PublicFiles and is
// sorted and deduplicated so the result is deterministic.
// RenderMemory renders completed turns in the order supplied. Each turn's body
// is embedded with its own headings demoted two levels, so the turn's "## Stage ·
// visit N" stays the structural section and a body heading can never look like a
// sibling turn (or like the system-written file list). The file list is
// system-written from PublicFiles, sorted and deduplicated, so the result is
// deterministic.
func RenderMemory(entries []MemoryEntry) string {
var b strings.Builder
for i, entry := range entries {
@@ -37,7 +40,7 @@ func RenderMemory(entries []MemoryEntry) string {
}
fmt.Fprintf(&b, "## %s · visit %d\n\n", entry.Stage, entry.Visit)
if entry.Output != "" {
b.WriteString(entry.Output)
b.WriteString(demoteHeadings(entry.Output))
if !strings.HasSuffix(entry.Output, "\n") {
b.WriteString("\n")
}
@@ -58,6 +61,58 @@ func RenderMemory(entries []MemoryEntry) string {
return b.String()
}
// demoteHeadings adds two '#' to every ATX heading outside a fenced code block,
// capped at H6. Fences and their contents are left exactly as written.
func demoteHeadings(markdown string) string {
var b strings.Builder
var fence fenceState
for _, chunk := range strings.SplitAfter(markdown, "\n") {
text := strings.TrimSuffix(chunk, "\n")
if fence.open() {
if fence.closes(text) {
fence = fenceState{}
}
b.WriteString(chunk)
continue
}
if marker, ok := openingFence(text); ok {
fence = marker
b.WriteString(chunk)
continue
}
b.WriteString(demoteATX(chunk))
}
return b.String()
}
func demoteATX(chunk string) string {
text := strings.TrimSuffix(chunk, "\n")
i := 0
for i < len(text) && i < 3 && text[i] == ' ' {
i++
}
j := i
for j < len(text) && text[j] == '#' {
j++
}
level := j - i
if level < 1 || level > 6 {
return chunk
}
if j < len(text) && text[j] != ' ' && text[j] != '\t' && text[j] != '\r' {
return chunk
}
add := 2
if level+add > 6 {
add = 6 - level
}
if add == 0 {
return chunk
}
suffix := chunk[len(text):]
return text[:j] + strings.Repeat("#", add) + text[j:] + suffix
}
func sortedUnique(values []string) []string {
if len(values) == 0 {
return nil