Octonote AI
Make your own →

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:

  1. Current repository files (what is on disk right now).
  2. Durable conversation records and observations (what the session stored: messages, tool calls, read results).
  3. 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.

Where the working set comes from
Where the working set comes from

What gets in before the first read

The fixture is a small synthetic repository, separate from Part 1's patch task:

FileContentRole in the experiment
src/slug.mjsMarked comments and filler at first; later replaced by an external runnerThe mutable file under inspection
attached noteA short text noteAttached explicitly to the first request
recent.txtA small fileRead 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.txtA harmless markerShould 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.

Attachments, rules and the first two calls
Attachments, rules and the first two calls

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.md and ~/.claude/CLAUDE.md (the second can be turned off with a flag). Only one wins.
  • Project: it tries filename families in order, AGENTS.md, then CLAUDE.md, then the deprecated CONTEXT.md. For each family it calls findUp(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 with AGENTS.md never also loads its CLAUDE.md, but a monorepo with AGENTS.md at two ancestor levels loads both.
  • Configured: paths and globs listed in instructions in 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.

How systemPaths() finds rule files
How systemPaths() finds rule files

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.

RouteWho triggers itStored asRe-evaluated each call?
Global / project / config rulesRuntime, every callNot stored; rebuilt by Instruction.system()Yes
AttachmentUser attaches a fileSynthetic user text partsNo, frozen at attach time
Tool readModel asks for readAssistant tool part with output + metadata.loadedNo, frozen at read time
Nearby ruleSide effect of a readAppended inside that read's outputNo, travels with the read
Attachments and nearby rules become model input
Attachments and nearby rules become model input

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.

A stale read stays in history
A stale read stays in history

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

OpenCode process boundaries
OpenCode process boundaries

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 - reserved when the model declares an input limit, where reserved defaults to min(20,000, max output tokens); otherwise context - max output tokens,
  • overflow when count >= usable. If compaction.auto is false, 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.

When and how compaction runs
When and how compaction runs

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_tokens if 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:

  1. The compaction user message, which projection turns into the text "What did we do so far?". The structured marker itself is never sent.
  2. The assistant summary.
  3. The retained tail (here, the recent.txt turn).
  4. 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.

Summary call and continuation
Summary call and continuation

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):

InformationOrdinary input before compactionSummary-request inputFirst ordinary continuation
Beginning of the old source observationPresentPresentAbsent
End of the old source observationPresentAbsentAbsent
Nested guidance appended to that readPresentAbsentAbsent
Attached note from the earlier turnPresentPresentAbsent
Recent recent.txt observationPresentAbsent, retained separatelyPresent
Replacement source now on diskAbsentAbsentAbsent

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.

What a 2,000-char clip loses
What a 2,000-char clip loses

Three reductions, three different boundaries

It is tempting to call all of this "context truncation". Vinoth separates three mechanisms that cut at different points:

ReductionWhere it cutsCodeLimitsIn this experiment
Read limitsWhen a file is acquiredtool/read.ts2,000 lines by default, 2,000 chars per line, 50 KB output capNot exercised; the read fit
PruningLater projection of old tool outputSessionCompaction.prune() + message-v2.tsOpt-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 serializationBuilding the summary inputcompaction.ts serialize()2,000 chars per tool resultObserved. 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?"

The fate of one read result
The fate of one read result

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.md again. 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):

Compaction, then an explicit reread
Compaction, then an explicit reread

And the dedup decision that differs between the two runs:

Instruction.resolve() on a reread
Instruction.resolve() on a reread

What to steal

Vinoth closes with an ownership table. The owners do not refresh on the same schedule, which is the whole problem:

InformationOwnerWhen it changesRelationship to the next request
Current working filesFilesystem and actual writersA user, tool or external process writes new bytesMust enter through an acquisition path
Recorded reads and attachmentsSession messages and partsAn observation or attachment expansion is recordedCan be selected, shortened, summarized or omitted
Global, project and configured rule textInstruction assemblySelected sources are read for ordinary task-call assemblyJoins history separately
Summary and retained-history boundaryCompaction machineryA summary is recorded and retention is selectedDetermines which records support continuation
Provider inputPrompt runtime and provider adapterA particular call is assembledIs 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] and tail_start_id are 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.

Debugging an ignored repository rule
Debugging an ignored repository rule

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.

The experiment harness
The experiment harness

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

  1. Why was the nested src/AGENTS.md missing from the first provider request?
  2. After the file changed on disk, why did the next request still show the old contents?
  3. What three things does the continuation request contain after compaction, in order, besides the rules?
  4. Why did the nested rule never reach the summary request, even though it reached earlier ordinary requests?
  5. Why did the final reread re-attach src/AGENTS.md only in the compacted run?
  6. Is "the rule was already loaded" a freshness guarantee?

Answers:

  1. Project rules are found by findUp, which searches upward from the working directory to the worktree root. It never descends into src/. The nested file only arrives when a read of a file under src/ triggers Instruction.resolve().
  2. Projection (toModelMessages) copies the stored state.output of the earlier read. It never reopens files. Only a new read brings new bytes.
  3. "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.
  4. serialize() clips each tool result to 2,000 characters before building the summary prompt, and read.ts appends nearby rules after the file content, so the rule fell beyond the cut.
  5. resolve() skips rules that extract() finds in metadata.loaded of selected reads. In the control run the old read was still selected; after compaction it was not, so the rule looked unloaded.
  6. 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.

Make a page like this. Free.Notes and diagrams side by side, written by you or by Claude Code and Codex. Publish it in one click.
Make your own, free