02 | Repository Context and Compaction
Sunil Tiwari · Oct 29, 2026 · 19 min read
Expanded from Part 2 of OpenCode Architecture by Vinoth Govindarajan, The Agent Stack.
Post: "OpenCode Architecture - Part 2: Repository Context and Compaction", published 28 September 2026. Subtitle: What reaches the model when the repository is larger than the conversation?
Code baseline: OpenCode v1.18.30 (commit 3104c14), the same version Vinoth tested. Every file and function named below was checked against that commit. Big-picture map of this part: the canvas in this project (Canvas or Split view)Part 1 followed the coding loop. Part 2 asks a narrower and more useful question: what information actually reaches the next provider call? Vinoth's answer is a mental model worth keeping: the model never sees "the repository" or "the conversation". It sees a bounded working set, assembled fresh for each call from three different kinds of state that must not be confused:
- Current repository files (what is on disk right now).
- Durable conversation records and observations (what the session stored: messages, tool calls, read results).
- The input assembled for one provider call (what was actually sent).
A file can exist without being included. An observation can stay stored without being selected. And an instruction can reach a request without telling us anything about whether a model would follow it. The rest of the post, and this note, is about the paths between those three layers.
The method is what makes the post credible. He ran the real OpenCode CLI against a local scripted provider over real loopback HTTP. Because the "model" is a script, every response is fixed, and any difference between runs comes from the runtime, not from model behaviour. He captured every outbound provider request, exported the session, and compared both with the files on disk.

What gets in before the first read
The fixture is a small synthetic repository, separate from Part 1's patch task:
| File | Content | Role in the experiment |
src/slug.mjs | Marked comments and filler at first; later replaced by an external runner | The mutable file under inspection |
| attached note | A short text note | Attached explicitly to the first request |
recent.txt | A small file | Read in the second invocation |
AGENTS.md (root) | "Verify current files." | Project guidance |
src/AGENTS.md (nested) | "Use the slug test command." | Nearby guidance (there is no real test command; it is just a marker) |
unread.txt | A harmless marker | Should never appear anywhere |
The first request asks OpenCode to inspect src/slug.mjs and attaches the note. The captured provider input already contains global guidance, root guidance, a configured rule file and the attached note. It does not yet contain the contents of src/slug.mjs or the nested src/AGENTS.md. Those two arrive later, by different routes. unread.txt never appears in any captured request.

Rules are discovered, not collected from every directory
OpenCode does not crawl the repository for instruction files. In session/instruction.ts, systemPaths() builds the rule set in three steps:
- Global: the first file that exists among OpenCode's global config
AGENTS.mdand~/.claude/CLAUDE.md(the second can be turned off with a flag). Only one wins. - Project: it tries filename families in order,
AGENTS.md, thenCLAUDE.md, then the deprecatedCONTEXT.md. For each family it callsfindUp(file, directory, worktree), which walks upward from the working directory to the worktree root and collects every same-named file on the way. The first family with any match wins and the loop stops. So a repo withAGENTS.mdnever also loads itsCLAUDE.md, but a monorepo withAGENTS.mdat two ancestor levels loads both. - Configured: paths and globs listed in
instructionsin the config. URLs are fetched separately with a 5 second timeout.
system() then reads them all and returns blocks that start with Instructions from: <path>.
The key consequence: the search goes up, never down. That is why the nested src/AGENTS.md is absent from the first request, and why the root CLAUDE.md fallback never appears in this fixture. Vinoth is careful to say this result is narrow: it shows what entered this run, not every file every configuration can load.
A small observation from the code: the comment above that loop says "The first project-level match wins so we don't stack AGENTS.md/CLAUDE.md from every ancestor". That describes the family choice. Within the chosen family, findUp does stack every ancestor, which is exactly what Vinoth describes.

An attachment takes a different route
The attached note is already in the first request because attachment expansion happens while the user message is being built, not in the agent loop. In session/prompt.ts, a file: part with mime text/plain is handled by calling the read tool's execute directly (with bypassCwdCheck and an empty message history). The result is stored as two synthetic text parts on the user message: one saying Called the Read tool with the following input: {...}, and one holding the file text.
"Synthetic" matters. The runtime wrote that text while expanding the attachment. It was not typed by the user, and it is not stored like an assistant-requested read (a tool part with state.output and metadata.loaded). Later, toModelMessages() in message-v2.ts skips the original text/plain file part ("text/plain and directory files are converted into text parts, ignore them") and sends only the synthetic text.
Simply mentioning src/slug.mjs in the prompt does nothing. Its contents only arrive when the scripted provider asks for a real read. That read returns the source and appends the nearby src/AGENTS.md, wrapped in a <system-reminder> block at the end of the tool output (tool/read.ts, after (End of file - total N lines)).
Vinoth's first distinction is the important one: not just what text is available, but how it entered the working set. A selected rule, an expanded attachment and a tool observation all add context, but they have different owners and lifecycles.
| Route | Who triggers it | Stored as | Re-evaluated each call? |
| Global / project / config rules | Runtime, every call | Not stored; rebuilt by Instruction.system() | Yes |
| Attachment | User attaches a file | Synthetic user text parts | No, frozen at attach time |
| Tool read | Model asks for read | Assistant tool part with output + metadata.loaded | No, frozen at read time |
| Nearby rule | Side effect of a read | Appended inside that read's output | No, travels with the read |

A read outlives the bytes it observed
After the first inspection, an external runner replaces the comment-only file with a real implementation:
export const slug = s => s.trim().toLowerCase();The next invocation continues the same session and asks OpenCode to inspect recent.txt. Before that new read happens, the provider request still contains the earlier src/slug.mjs observation. The new implementation is on disk; its bytes are not in the request. Vinoth checked this precisely: the old tool-result body sent to the provider matches the stored read output byte for byte, and the independently checked current file has different bytes.
The first read was correct when it happened. It is now a historical observation.
Why this happens is plain in the code. Each loop step in SessionPrompt.runLoop calls MessageV2.filterCompactedEffect(sessionID) to select messages, then MessageV2.toModelMessagesEffect(msgs, model) to project them into provider messages. Projection copies part.state.output for each completed tool part. It never reopens the file a past read pointed at. There is no freshness check, no file watcher invalidating old tool results, no hash comparison.
Common misconception: "the agent knows the file changed because it is the same path." It does not. The path string is identical in both states; only a new read can bring new bytes. A session can keep perfect conversational continuity while describing an older repository.
Ordinary guidance takes yet another path. In runLoop, each step gathers sys.environment(model), instruction.system(), MCP instructions and skills, puts them into system, and llm/request.ts prepare() prepends the agent prompt (or the provider default prompt) plus any user system text. AGENTS.md is one input to the system prompt, not the system prompt itself.

Vinoth's ownership picture of the run (redrawn from his figure):

Two details he flags: durable state and working files are separate kinds of state, not separate security boundaries; and the CLI-to-application hop stays in-process while the hop to the provider is real HTTP. That second point is what makes the experiment trustworthy: he could inspect what OpenCode submitted rather than infer it from the transcript.
Compaction creates a different kind of request
The experiment now forks into two fresh repositories with their own sessions: one with automatic compaction disabled (compaction.auto: false), one with it enabled. Same files, same scripted read sequence.
After the recent.txt read, the scripted provider reports artificially high token usage. This is a fixture control, not a measurement. It works because session/overflow.ts decides overflow purely from recorded usage and model limits:
count = tokens.total(or input + output + cache read + cache write),usable = model.limit.input - reservedwhen the model declares an input limit, wherereserveddefaults tomin(20,000, max output tokens); otherwisecontext - max output tokens,- overflow when
count >= usable. Ifcompaction.autoisfalse, it always returns false.
On the next loop step, runLoop sees the last finished assistant message overflowed, calls compaction.create(...) (a new user message holding a compaction part), and continues. The following step pops that task and runs compaction.process(...). In the enabled case this produces two different provider calls: a summary request, then an ordinary continuation. They do not receive the same working set.

The summary request receives the older head
SessionCompaction.select() in compaction.ts divides the selected conversation into an older part to summarize and a recent part to keep. Vinoth calls them the head and the tail. By default the tail is chosen by a token budget, walking turns from newest to oldest:
preserve_recent_tokensif configured, else 25% of usable context, clamped between 2,000 and 15,000 tokens;- optionally limited further by
tail_turns(keep at most N recent user turns); - if a whole turn does not fit,
splitTurn()may keep only its later messages.
For the experiment he configured retention to keep exactly the most recent user turn, so the recent.txt request, its read and its response became the tail, and the earlier source-inspection turn became the head. He stresses this is an experiment control, not OpenCode's universal default.
The summary request gets a text serialization of the head only. serialize() turns each message into lines like [User]: ..., [Assistant tool call]: read({...}) and [Tool result]: ..., and buildPrompt() (from @opencode-ai/core/session/compaction) wraps them in <conversation> tags with a summary template. The call runs as the hidden compaction agent, with tools: {} and system: [], so its system input is the compaction agent prompt ("You are a context summarization agent...") rather than the normal provider prompt plus rules.
The continuation receives the summary and retained history
The scripted provider returns a fixed summary (tracing label removed):
"Earlier inspection completed. Re-read mutable files before continuing."
The wording and its omissions are deliberate. OpenCode stores it as an assistant message with summary: true, and records tail_start_id (where the retained tail starts) on the compaction part.
On the next call, MessageV2.filterCompacted() rebuilds history for the model and reorders it:
- The compaction user message, which projection turns into the text "What did we do so far?". The structured marker itself is never sent.
- The assistant summary.
- The retained tail (here, the
recent.txtturn). - A synthetic user message: "Continue if you have next steps, or stop and ask for clarification if you are unsure how to proceed."
The code comment says it plainly: filterCompacted reorders messages for model consumption ([compaction-user, summary, ...retained tail..., continue-user]), so array position is not chronological.
This is Vinoth's key distinction: durable history and continuation history are related, but they are not the same representation. In the control case none of this happens: no summary request, no automatic continuation, and the old source observation stays selected when the next invocation begins.

The rule disappeared before the summary was written
There is another boundary inside the compaction path, and it is the post's sharpest finding.
The first source read returned the whole comment-only fixture, including its end marker, followed by the nearby rule from src/AGENTS.md. That full result fit within the read tool's limits, and both the source ending and the nested guidance reached an ordinary provider request.
They did not reach the summary request. The reason is in compaction.ts:
const TOOL_OUTPUT_MAX_CHARS = 2_000
const truncate = (value: string) =>
value.length <= TOOL_OUTPUT_MAX_CHARS
? value
: `${value.slice(0, TOOL_OUTPUT_MAX_CHARS)}\n[truncated]`serialize() applies truncate to every completed tool result before the summary prompt is built. The beginning of the old source survives. The end, including the appended <system-reminder> with the nested rule, falls past character 2,000. Because read.ts appends nearby rules after the file content, any read longer than about 2,000 characters loses its nearby guidance in the summarizer's view.
His presence table from the captured requests (presence, not the exact request):
| Information | Ordinary input before compaction | Summary-request input | First ordinary continuation |
| Beginning of the old source observation | Present | Present | Absent |
| End of the old source observation | Present | Absent | Absent |
| Nested guidance appended to that read | Present | Absent | Absent |
| Attached note from the earlier turn | Present | Present | Absent |
Recent recent.txt observation | Present | Absent, retained separately | Present |
| Replacement source now on disk | Absent | Absent | Absent |
Two different mechanisms explain the omissions:
- The source ending and nested rule never reached the summarizer: the tool result was clipped first.
- The attached note and the beginning of the source did reach the summarizer, but the fixed summary left them out by design.
Neither says a model "forgot" anything. And notice the last row: the new implementation is absent everywhere, because nothing in compaction rereads files.
The summary request is not instruction-free; it has its own system input (the compaction agent prompt). What changes is narrower: the ordinary global, root and configured rule blocks are absent from the summary request, then reappear in the continuation. That follows ownership: runLoop calls instruction.system() on every ordinary step, so those rules come back through ordinary assembly. The summary does not need to preserve them.

Three reductions, three different boundaries
It is tempting to call all of this "context truncation". Vinoth separates three mechanisms that cut at different points:
| Reduction | Where it cuts | Code | Limits | In this experiment |
| Read limits | When a file is acquired | tool/read.ts | 2,000 lines by default, 2,000 chars per line, 50 KB output cap | Not exercised; the read fit |
| Pruning | Later projection of old tool output | SessionCompaction.prune() + message-v2.ts | Opt-in (compaction.prune, default false). Skips the last 2 user turns, protects the newest 40,000 tokens of tool output, only acts if over 20,000 tokens would be freed, never prunes skill. Marked parts project as [Old tool result content cleared] | Disabled |
| Compaction serialization | Building the summary input | compaction.ts serialize() | 2,000 chars per tool result | Observed. Full read still in the session export |
So when context goes missing, the useful question is not "did summarization lose it?" but "where did it stop flowing?"

Rereading changes the working set again
After compaction, the full old read still exists in the session export, with no pruning mark. It is simply no longer selected: filterCompacted() walks back only to the compaction boundary and tail_start_id. Storage keeps the evidence; continuation uses a smaller projection.
The final invocation explicitly asks OpenCode to reread src/slug.mjs. The read returns the replacement implementation, so the new bytes finally enter provider-facing history, and the nested guidance comes back with them. But only in the compacted case:
- No compaction (control): the new read does not append
src/AGENTS.mdagain. The old read is still in selected history and still records it as loaded. - Compacted: the earlier read is no longer in selected history, so the new read re-attaches
src/AGENTS.md.
The mechanism is in Instruction.resolve(). It walks upward from the file being read toward the project directory and skips any candidate that is (a) already a system path, (b) already "loaded" according to extract(messages), or (c) already claimed for this assistant message. extract() scans completed read tool parts in the messages it is given and collects metadata.loaded, skipping parts marked time.compacted. After compaction, the messages it is given come from filterCompacted(), so the old loaded record is gone and the rule is attached again. (The per-message claim set is cleared at the end of every assistant message via instruction.clear.)
Nothing here says the rule changed. It shows that selected history decides whether nearby guidance counts as already loaded. A side effect worth knowing from the same code: pruning also sets time.compacted, so a pruned read would also let its nearby rule be re-attached.
The control case makes the freshness problem stark. After its final reread, the provider input contains both the old and new source observations. A fresh read adds new evidence. It does not erase the old evidence. In Vinoth's words, "refreshing a fact and reconciling history are separate jobs."
Vinoth's lifecycle after the recent-file inspection, compaction-enabled run (redrawn from his figure):

And the dedup decision that differs between the two runs:

What to steal
Vinoth closes with an ownership table. The owners do not refresh on the same schedule, which is the whole problem:
| Information | Owner | When it changes | Relationship to the next request |
| Current working files | Filesystem and actual writers | A user, tool or external process writes new bytes | Must enter through an acquisition path |
| Recorded reads and attachments | Session messages and parts | An observation or attachment expansion is recorded | Can be selected, shortened, summarized or omitted |
| Global, project and configured rule text | Instruction assembly | Selected sources are read for ordinary task-call assembly | Joins history separately |
| Summary and retained-history boundary | Compaction machinery | A summary is recorded and retention is selected | Determines which records support continuation |
| Provider input | Prompt runtime and provider adapter | A particular call is assembled | Is the submitted working set, not all available state |
His three takeaways, as a checklist for anyone building an agent runtime:
Make the selected input inspectable
- Capture the exact outbound provider request, not just the transcript. A stored read, a displayed transcript and a captured request answer different questions.
- When a rule is missing, check how it was discovered and whether it reached the outbound request.
- When an old fact persists, compare the recorded observation with the current file.
- Around compaction, inspect the input to the summary, not just the summary.
Keep provenance when representations change
- Every observation stays attributable to the file and acquisition step that produced it.
- Summaries stay distinguishable from the observations they summarize.
- Make shortening boundaries visible (OpenCode's
[truncated]andtail_start_idare good starts). - Don't count only tool calls: attachments enter as synthetic user text, not tool results.
Reobserve mutable facts when the decision depends on them
- Reread decision-critical files when another writer may have changed them, when switching checkouts, or when selected history no longer holds the needed detail.
- Treat "already loaded" as deduplication, not freshness: the resolver checks loaded-path metadata, not current bytes.
- Remember capacity and freshness are separate problems: a compact continuation can still describe an old repo, and a large one can hold old and new observations with the conflict unresolved.
One extra idea that follows from the code, offered in the same spirit: since nearby rules are appended after file content, a summarizer that clips from the end will always drop them first. Putting provenance and rules before content, or excluding them from clipping, would make them survive compaction.

Source baseline and experiment notes
- Baseline: OpenCode v1.18.30, with source research and recorded experiments.
- Real OpenCode CLI, real file reads, a local scripted provider. Pruning disabled; controlled usage reports exercised the compaction path.
- No model inference occurred. The experiment tests context handling, not model reasoning or summary quality.
- Post-run checks compared captured provider requests, exported session state and current files. Vinoth is explicit that these establish consistency, not independent proof of execution.
- Companion lab to reproduce it: the-agent-stack-labs, 02-repository-context-compaction.
Post vs current code. Everything the post claims matches v1.18.30. I also checked the latest release at the time of writing (v1.19.5): the same constants are still there (TOOL_OUTPUT_MAX_CHARS = 2_000, PRUNE_PROTECT = 40_000, PRUNE_MINIMUM = 20_000, read limits of 2,000 lines and 50 KB, "What did we do so far?"). One thing to watch: a v2 core is being ported into packages/core (it has its own session/compaction.ts with select() and buildPrompt()), so these mechanics may move there later.

Next in the series: the working set supports a proposed action, but a different boundary decides whether the runtime may execute it. Part 3 follows that: Tool Execution and Permission Boundaries. Vinoth leaves a question worth sitting with: when a coding agent misses a repository rule, what evidence would let you distinguish failed loading, loss during compaction, and failure to follow an included instruction? (The decision flowchart in "What to steal" is one answer.)
Quick self-check
- Why was the nested
src/AGENTS.mdmissing from the first provider request? - After the file changed on disk, why did the next request still show the old contents?
- What three things does the continuation request contain after compaction, in order, besides the rules?
- Why did the nested rule never reach the summary request, even though it reached earlier ordinary requests?
- Why did the final reread re-attach
src/AGENTS.mdonly in the compacted run? - Is "the rule was already loaded" a freshness guarantee?
Answers:
- Project rules are found by
findUp, which searches upward from the working directory to the worktree root. It never descends intosrc/. The nested file only arrives when areadof a file undersrc/triggersInstruction.resolve(). - Projection (
toModelMessages) copies the storedstate.outputof the earlier read. It never reopens files. Only a new read brings new bytes. - "What did we do so far?" (the projected compaction marker), the stored summary, the retained tail, then the synthetic "Continue if you have next steps..." message.
serialize()clips each tool result to 2,000 characters before building the summary prompt, andread.tsappends nearby rules after the file content, so the rule fell beyond the cut.resolve()skips rules thatextract()finds inmetadata.loadedof selected reads. In the control run the old read was still selected; after compaction it was not, so the rule looked unloaded.- No. It is a deduplication decision based on path metadata in selected history. It says nothing about whether the rule's bytes are still current.
Source and credit
All of the experiments, findings, tables and framing above are Vinoth Govindarajan's. This note adds code walkthroughs and diagrams on top of his work.
- Post: OpenCode Architecture - Part 2: Repository Context and Compaction (28 September 2026)
- Publication: The Agent Stack
- Author: Vinoth Govindarajan on LinkedIn · GitHub @vingov
- Companion lab: the-agent-stack-labs / 02-repository-context-compaction
- OpenCode repo: anomalyco/opencode (formerly sst/opencode), files at v1.18.30:
- session/instruction.ts:
systemPaths(),system(),resolve(),extract() - core fs-util.ts findUp
- tool/read.ts: read limits and nearby-rule append
- session/prompt.ts: attachment expansion and
runLoop - session/message-v2.ts:
toModelMessages(),filterCompacted() - session/compaction.ts:
select(),serialize(),prune(),process() - session/overflow.ts:
isOverflow(),usable() - session/llm/request.ts: system-input assembly
- session/instruction.ts: