CH 05 · Context Engineering and Memory · 18/18
Read as one pageRead the source yourself
Five files, in the order this chapter built the idea. Each link is pinned to the commit the excerpts came from.
- Context is built per call. In pi's
packages/agent/src/agent-loop.ts, readstreamAssistantResponse. Decide whethertransformContextrewrites the stored transcript or only the list for this call. The localmessagesvariable is the request. The assistant reply is appended tocontext.messages; the trimmed list is not written back. The test "should apply transformContext before convertToLlm" inpackages/agent/test/agent-loop.test.tsis the worked example: the context holds four old messages, the loop appends the new prompt, and the transform keeps the last two. - Tool output is capped at the boundary. In OpenCode's
packages/core/src/tool-output.ts, readtruncate, then the call sitetoolOutput.truncateinpackages/core/src/session/runner/step.ts. Ifmetadata.truncatedis already true or false, the result comes back unchanged. The shell keeps the tail inpackages/core/src/shell.ts, andpackages/core/src/shell/result.tscopies that boolean onto the metadata. - Layers have a fixed order. In OpenClaw's
src/agents/system-prompt-context-files.ts, readCONTEXT_FILE_ORDERandbuildProjectContextSection. Three names get a guidance line (soul, memory, user).MEMORY.mdsorts last among the named files.buildSystemPromptplaces that block under "Workspace Files (injected)" (src/agents/system-prompt.ts). The tool list for this run is thebuildSystemPromptToolingSectioncall just below, at line 656. - Memory is surfaced, not always loaded. In OpenClaw's
src/agents/workspace.ts, readfilterBootstrapFilesForSession. A private chat keeps the workspace-rootMEMORY.md. A group or channel drops that root file. A helper's prompt keeps onlyAGENTS.md, and a cron run keeps four names. - A hit is an address, then a slice. In OpenClaw's
extensions/memory-core/src/memory-tool-contract.ts, readMEMORY_SEARCH_TOOL_CONTRACTandbuildMemoryPromptSection. When both tools are on, the prompt says to search, thenmemory_getthe needed lines.buildMemoryReadResulttakes up to 120 lines whenlinesis omitted (read-file-shared.ts).buildMemoryReadResultFromSlicemay 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.