Skip to slide
078 / 221

CH 05 · Context Engineering and Memory · 18/18

Read as one page

Read the source yourself

Five files, in the order this chapter built the idea. Each link is pinned to the commit the excerpts came from.

  1. Context is built per call. In pi's packages/agent/src/agent-loop.ts, read streamAssistantResponse. Decide whether transformContext rewrites the stored transcript or only the list for this call. The local messages variable is the request. The assistant reply is appended to context.messages; the trimmed list is not written back. The test "should apply transformContext before convertToLlm" in packages/agent/test/agent-loop.test.ts is the worked example: the context holds four old messages, the loop appends the new prompt, and the transform keeps the last two.
  2. Tool output is capped at the boundary. In OpenCode's packages/core/src/tool-output.ts, read truncate, then the call site toolOutput.truncate in packages/core/src/session/runner/step.ts. If metadata.truncated is already true or false, the result comes back unchanged. The shell keeps the tail in packages/core/src/shell.ts, and packages/core/src/shell/result.ts copies that boolean onto the metadata.
  3. Layers have a fixed order. In OpenClaw's src/agents/system-prompt-context-files.ts, read CONTEXT_FILE_ORDER and buildProjectContextSection. Three names get a guidance line (soul, memory, user). MEMORY.md sorts last among the named files. buildSystemPrompt places that block under "Workspace Files (injected)" (src/agents/system-prompt.ts). The tool list for this run is the buildSystemPromptToolingSection call just below, at line 656.
  4. Memory is surfaced, not always loaded. In OpenClaw's src/agents/workspace.ts, read filterBootstrapFilesForSession. A private chat keeps the workspace-root MEMORY.md. A group or channel drops that root file. A helper's prompt keeps only AGENTS.md, and a cron run keeps four names.
  5. A hit is an address, then a slice. In OpenClaw's extensions/memory-core/src/memory-tool-contract.ts, read MEMORY_SEARCH_TOOL_CONTRACT and buildMemoryPromptSection. When both tools are on, the prompt says to search, then memory_get the needed lines. buildMemoryReadResult takes up to 120 lines when lines is omitted (read-file-shared.ts). buildMemoryReadResultFromSlice may shorten that to the character budget and append the continuation note (lines 15 to 26 and 29 to 51).

Exercise: clone pi at that commit and, in the test from step 1, change messages.slice(-2) to messages.slice(-1). Before you run it, write down which expects fail. Both toBe(2) checks fail, because the lengths become 1: the transform runs before convertToLlm, and the converter in that test only counts what the transform returned.

Finished this idea?

Your learning progress stays in this browser.