Merge: short essential memory per stage; full history on demand

This commit is contained in:
2026-11-04 13:01:16 +00:00
27 changed files with 912 additions and 128 deletions
+2 -2
View File
@@ -209,7 +209,7 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
// artifactsPrompt tells an agent stage where it may write the files it
// produces. The turn directory itself belongs to the server: input.md,
// memory.md and output.md are written by the runner and output.md comes from
// memory.md, history.md and output.md are written by the runner and output.md comes from
// the model's final message. The only writable artifact scopes are this
// visit's private/ directory and the run's shared public/ directory, matching
// the exact paths permissionRules grants. It is empty when the runtime provided
@@ -231,7 +231,7 @@ func artifactsPrompt(directory string, access ArtifactAccess) string {
fmt.Fprintf(&b, " Save artifacts for later stages under %s; files there are shared by the run.", access.WriteShared)
}
if writable {
b.WriteString(" Do not write input.md, memory.md or output.md yourself; the server owns those and writes output.md from your final message.")
b.WriteString(" Do not write input.md, memory.md, history.md or output.md yourself; the server owns those and writes output.md from your final message.")
} else {
b.WriteString(" The server records the turn files as artifacts.")
}
+1 -1
View File
@@ -36,7 +36,7 @@ func TestArtifactsPromptStatesWritableScopes(t *testing.T) {
"/data/artifacts/1/2",
"/data/artifacts/1/2/private",
"/data/artifacts/1/public",
"do not write input.md, memory.md or output.md",
"do not write input.md, memory.md, history.md or output.md",
} {
if !strings.Contains(strings.ToLower(prompt), strings.ToLower(want)) {
t.Fatalf("prompt missing %q: %q", want, prompt)
+63 -29
View File
@@ -8,6 +8,7 @@ import (
"sort"
"strings"
"time"
"unicode/utf8"
"git.a-wan.net/alan/pipelines/internal/turn"
)
@@ -57,52 +58,54 @@ func modelPrompt(def Definition, spec ModelSpec, input Values) (string, error) {
toolsLine = "This call has these stage tools: " + strings.Join(tools, ", ") + "."
}
// Essential memory (memory.md) is short and capped, so it is inlined for
// every stage: the stage needs no read call to start, and each model call
// re-sends only this bounded context. The full history (history.md) is
// never inlined; a stage with the read tool is pointed at it and at input.md
// for on-demand detail.
memory, readErr := os.ReadFile(def.Turn.Memory)
if readErr != nil {
return "", fmt.Errorf("model stage %s: read turn memory: %w", def.Key, readErr)
}
var b strings.Builder
// Receiving runtime context must not require adding filesystem tools to a
// web-only (or otherwise restricted) stage. Inline it whenever read is not
// declared, without widening the harness's permissions or changing a workflow.
if !slices.Contains(tools, "read") {
memory, readErr := os.ReadFile(def.Turn.Memory)
if readErr != nil {
return "", fmt.Errorf("model stage %s: read turn memory: %w", def.Key, readErr)
canRead := slices.Contains(tools, "read")
switch {
case !canRead && len(tools) == 0:
b.WriteString("This call has no tools, so the server included the turn files below.\n\n")
case !canRead:
b.WriteString("The read tool is not enabled, so the server included the turn files below. Use this supplied context; no extra filesystem access is needed.\n\n")
}
writeTurnFile(&b, "memory.md", def.Turn.Memory, capInline(string(memory), turn.EssentialCap, def.Turn.Memory))
if canRead {
b.WriteString("Rely on this essential memory first. Read on demand only, when you need more detail:\n")
fmt.Fprintf(&b, "- Input (full run task and previous stage output): %s\n", def.Turn.Input)
if def.Turn.History != "" {
fmt.Fprintf(&b, "- History (every earlier turn in full; large): %s\n", def.Turn.History)
}
b.WriteString("\n")
} else {
input, readErr := os.ReadFile(def.Turn.Input)
if readErr != nil {
return "", fmt.Errorf("model stage %s: read turn input: %w", def.Key, readErr)
}
if len(tools) == 0 {
b.WriteString("This call has no tools, so the server included the turn files below.\n\n")
} else {
b.WriteString("The read tool is not enabled, so the server included the turn files below. Use this supplied context; no extra filesystem access is needed.\n\n")
}
fmt.Fprintf(&b, "# memory.md (%s)\n\n%s", def.Turn.Memory, string(memory))
if len(memory) > 0 && !strings.HasSuffix(string(memory), "\n") {
b.WriteString("\n")
}
b.WriteString("\n")
fmt.Fprintf(&b, "# input.md (%s)\n\n%s", def.Turn.Input, string(input))
if len(input) > 0 && !strings.HasSuffix(string(input), "\n") {
b.WriteString("\n")
}
b.WriteString("\n")
} else {
b.WriteString("Read these two files before working:\n")
fmt.Fprintf(&b, "- Memory: %s\n", def.Turn.Memory)
fmt.Fprintf(&b, "- Input: %s\n\n", def.Turn.Input)
b.WriteString("Memory is the accumulated markdown of the run's completed turns, including the files each turn added to public/. Input is the run prompt on the first visit and the previous visit's output afterwards. Read both files before acting.\n\n")
writeTurnFile(&b, "input.md", def.Turn.Input, capInline(string(input), InlineInputCap, def.Turn.Input))
}
b.WriteString("Stage instructions:\n\n")
b.WriteString(strings.TrimSpace(spec.Prompt))
if changed := serverChangedFiles(input); len(changed) > 0 {
b.WriteString("\n\nServer-captured changed files for this run (verified from the workspace, not a model claim):\n")
for _, name := range changed {
for i, name := range changed {
if i == maxPromptChangedFiles {
fmt.Fprintf(&b, "- ... and %d more\n", len(changed)-i)
break
}
fmt.Fprintf(&b, "- %s\n", name)
}
b.WriteString("\nUse this list to distinguish this run's work from pre-existing dirty files.")
}
b.WriteString("\n\nProduce ")
b.WriteString(def.Turn.Output)
b.WriteString(" as markdown; return its complete content as your final message (the server writes that file). The only required section is the outcome, for example:\n\n# outcome\n")
b.WriteString(" as markdown; return its complete content as your final message (the server writes that file). Start it with a short # handoff section (at most about 1 KB): what you did, files changed, and open issues or findings the next stage must act on. The next stage receives only that section as essential memory; the rest of your output stays in history. The only required section is the outcome, for example:\n\n# handoff\n...\n\n# outcome\n")
b.WriteString(preferredOutcome(outcomes))
fmt.Fprintf(&b, "\n\nAllowed outcomes: %s.\n\nEverything else is free-form markdown for the next stage and the operator. The server does not parse or validate any other section. Return the complete output.md content as your final message; do not wrap it in a JSON envelope.\n", strings.Join(outcomes, ", "))
fmt.Fprintf(&b, "\nExecution time: %s. Timezone: %s.\n", time.Now().Format(time.RFC3339), time.Local.String())
@@ -118,6 +121,37 @@ func modelPrompt(def Definition, spec ModelSpec, input Values) (string, error) {
// serverChangedFiles reads the runner's reserved changed-path list from stage
// input, accepting the []string the runner supplies and the []any JSON decoding
// produces for a replayed handoff. Other values are ignored.
// InlineInputCap bounds input.md when it is inlined for a stage without the
// read tool. Such a stage cannot read on demand, so the cap is generous; it only
// stops one pathological previous output from dominating every call.
const InlineInputCap = 32 << 10
// maxPromptChangedFiles bounds the bound server_changed_files list in the
// prompt; the complete list stays in the stage input.
const maxPromptChangedFiles = 50
// writeTurnFile embeds one server-written turn file under a heading naming it.
func writeTurnFile(b *strings.Builder, name, path, content string) {
fmt.Fprintf(b, "# %s (%s)\n\n%s", name, path, content)
if content != "" && !strings.HasSuffix(content, "\n") {
b.WriteString("\n")
}
b.WriteString("\n")
}
// capInline keeps the head of content within limit bytes (at a rune boundary)
// and names the file holding the rest.
func capInline(content string, limit int, path string) string {
if len(content) <= limit {
return content
}
cut := limit
for cut > 0 && !utf8.RuneStart(content[cut]) {
cut--
}
return content[:cut] + fmt.Sprintf("\n\n_[truncated: %d of %d bytes shown; full file at %s]_\n", cut, len(content), path)
}
func serverChangedFiles(input Values) []string {
raw, ok := input["server_changed_files"]
if !ok {
@@ -0,0 +1,60 @@
package stage
import (
"os"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/turn"
)
// TestModelPromptInlinesEssentialMemoryAndPointsAtHistory: every stage gets the
// capped essential memory inline; the full history is never inlined, and a
// stage with read is pointed at input.md and history.md for on-demand detail.
func TestModelPromptInlinesEssentialMemoryAndPointsAtHistory(t *testing.T) {
for _, toolset := range []string{"read\nedit", "websearch", ""} {
t.Run(strings.ReplaceAll(toolset, "\n", "-"), func(t *testing.T) {
def := turnDefinition(t)
def.Blocks["tools"] = toolset
def.Turn.History = filepath.Join(def.Turn.Dir, "history.md")
files := map[string]string{
def.Turn.Memory: "# Essential memory\n\nreviewer finding: lock leak\n" + strings.Repeat("m", 2*turn.EssentialCap),
def.Turn.Input: "full previous output\n",
def.Turn.History: "FULL HISTORY BODY\n",
}
for path, content := range files {
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
}
spec, err := (ModelStage{}).Spec(def)
if err != nil {
t.Fatal(err)
}
prompt, err := modelPrompt(def, spec, nil)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(prompt, "reviewer finding: lock leak") || !strings.Contains(prompt, "_[truncated: ") {
t.Fatalf("essential memory not inlined with its cap: %q", prompt)
}
if strings.Contains(prompt, strings.Repeat("m", turn.EssentialCap+1)) {
t.Fatal("inlined memory exceeded its cap")
}
if strings.Contains(prompt, "FULL HISTORY BODY") {
t.Fatal("history.md was inlined")
}
if !strings.Contains(prompt, "# handoff") {
t.Fatal("prompt does not ask for a handoff section")
}
canRead := strings.Contains(toolset, "read")
if got := strings.Contains(prompt, def.Turn.History); got != canRead {
t.Fatalf("history path named = %v, want %v: %q", got, canRead, prompt)
}
if got := strings.Contains(prompt, "full previous output"); got == canRead {
t.Fatalf("input.md inlined = %v with read = %v", got, canRead)
}
})
}
}
+1 -1
View File
@@ -237,7 +237,7 @@ func TestAgentGeneratePromptCarriesToolsEditScopeAndShellCommands(t *testing.T)
def.Turn.Output,
def.Turn.Private,
def.Turn.Public,
"Do not write input.md, memory.md or output.md",
"Do not write input.md, memory.md, history.md or output.md",
} {
if !strings.Contains(promptBody, want) {
t.Fatalf("agent prompt missing %q: %s", want, promptBody)
+5 -2
View File
@@ -10,14 +10,17 @@ import (
// Values are runtime data, not the prose output contract in a definition.
type Values map[string]any
// TurnPaths is the runtime-provided file layout for one model visit. Input and
// memory are read by the model; Output is written by the server from the model's
// TurnPaths is the runtime-provided file layout for one model visit. Memory is
// the short essential memory the prompt inlines; Input and History are the full
// previous output and run history, read only on demand (History is empty for
// callers that predate it). Output is written by the server from the model's
// returned markdown. Private belongs to this visit; Public is shared by every
// stage in the run.
type TurnPaths struct {
Dir string
Input string
Memory string
History string
Output string
Private string
Public string