Context Engineering for Coding Agents
Context engineering is the discipline of deciding what a coding agent sees at every step — which files, tools, prior results, and runtime facts enter the model's context window, and what stays out. It matters more than clever prompting: a large-language model can only reason over what it can see, so the quality of an agent's edits is bounded by the quality of its context. This guide covers context windows and token budgets, retrieval versus graph-based context, tool-result management, durable memory, and the cost of it all — with concrete notes on how SlicerCode assembles graph- and runtime-grounded context under a bounded budget.
- What Is Context Engineering?
- Why Context, Not the Prompt, Determines Agent Quality
- Context Windows and Token Budgets
- Retrieval vs Graph-Based Context
- Runtime-Grounded Context: What Actually Ran
- Managing Tool Results: Pruning, Stubbing, and Compaction
- Memory and Project Structure
- The Cost and Latency of Context
- Putting It Together: Context Engineering with SlicerCode
What Is Context Engineering?
Context engineering is the practice of assembling everything a model sees on each step of a task — and, just as deliberately, everything it does not. Every LLM call is stateless: the model knows only what is in its context window at that instant. Prompt engineering wordsmiths a single instruction; context engineering governs the entire working set around that instruction — the system prompt, the tool definitions, retrieved source code, the results of previous tool calls, project memory, and the running conversation history. For a deeper look at wording the instruction itself, see prompt engineering for developers; this page is about the payload it rides on.
For a coding agent the relevant "context" is your codebase, which is orders of magnitude larger than any context window. You cannot paste a repository into a prompt, so the core problem becomes selection and compression: getting the few thousand tokens that actually matter for *this* step in front of the model, in a form it can use. Do that well and the agent writes code that fits your project; do it poorly and it invents plausible-but-wrong APIs.
It is a discipline rather than a one-time prompt because context is dynamic. In a multi-step agent loop the context grows with every file read, search, and test run. Managing that growth — pruning stale results, refreshing what changed, keeping the signal-to-noise ratio high — is the difference between an agent that stays on track and one that quietly drifts off it.
- System prompt and rules — the agent's standing instructions and guardrails
- Tool definitions — the functions the agent can call and their schemas
- Retrieved context — the specific code, docs, and flows relevant to the task
- Tool results — the observations returned by file reads, searches, and test runs
- Memory — durable facts about the project that survive across turns
- History — the prior messages in the current conversation
Why Context, Not the Prompt, Determines Agent Quality
A model can only reason over what it can see. The dominant failure mode of coding agents is not weak reasoning — it is missing or wrong context. A perfectly worded instruction pointed at the wrong files produces a confident hallucination; the same instruction with the right call path, the right types, and the existing utilities in view produces a correct edit. Grounding is what separates a demo from a tool you trust on real code.
Consider a request as ordinary as "add validation to the transfer endpoint." To do it correctly the model needs the route handler, the request DTO, the validation helpers your repo already ships, and the downstream services on the path — otherwise it reinvents an API that does not exist, duplicates a validator you already have, or validates the wrong field. None of that is a prompting problem; it is a context problem. This is why context engineering, not prompt phrasing, is the lever that moves accuracy.
How SlicerCode does it: the agent is grounded in the analyzer's own understanding of your project before it writes a line. It consults your call graph, the flow you are touching, and real runtime values, so its edits match how the code actually behaves rather than how a generic model guesses it might. See the AI coding agent overview and our primer on AI coding agents for how grounding changes the output.
Context Windows and Token Budgets
A context window is the maximum number of tokens a model can attend to in a single call — the sum of everything you send plus everything it generates. Windows have grown from a few thousand tokens to hundreds of thousands, which tempts teams to simply stuff more in. But a bigger window is a capacity, not a strategy: what you can fit and what you should send are different questions.
Long contexts degrade in practice. Models exhibit *context rot* and a well-documented "lost in the middle" effect, where facts buried in the center of a long prompt are attended to less reliably than those at the edges. Latency and cost also scale with token count on every single step, and an agent may take dozens of steps. Flooding the window with marginally relevant code makes the agent slower, more expensive, and often *less* accurate — the important lines get drowned out.
The practical answer is a token budget: treat the window as a fixed resource and allocate it deliberately across the system prompt, tool definitions, retrieved context, history, and — critically — headroom for the model's output. Retrieve precisely rather than dumping whole files; keep the highest-signal material near the top and bottom.
How SlicerCode does it: the agent reprocesses only a bounded context per turn, tunable via slicercode.agentContext (compact ≈24K, balanced ≈40K, full ≈64K, or a custom token count). Smaller budgets mean faster, non-stalling turns; see the token & context settings in the docs. For the model-side fundamentals of windows and tokens, see LLMs for developers.
- System prompt + rules — kept stable so it can be cached
- Tool schemas — only the tools relevant to the task
- Retrieved code — precise slices, not whole files
- Recent history — pruned as it grows stale
- Output headroom — always reserve room for the response
Retrieval vs Graph-Based Context
The most common way to select context is retrieval-augmented generation (RAG): chunk the codebase, embed each chunk into a vector, and at query time fetch the nearest neighbors to the request. It is fast, language-agnostic, and genuinely useful for fuzzy, natural-language lookups like documentation and prose. For code, though, embeddings have sharp limits — chunking splits functions from their callers, nearest-neighbor search returns lexically similar but semantically irrelevant snippets, and vectors are blind to the relationships that actually govern behavior: what calls what, what type flows where.
Graph-based context takes the opposite approach. Instead of guessing by similarity, it builds a structural model of the code — a call graph, data-flow (def-use) edges, and object-flow — and retrieves along real relationships. Ask about a function and you can pull exactly its callers, its callees, the types on the path, and the external systems it touches, with no irrelevant neighbors. For an agent editing code, that precision is worth far more than fuzzy recall: it gives the model the true blast radius of a change.
The two are complementary — embeddings for docs and free-text, the graph for code structure — but for edits on a real repo the graph is the higher-signal source. Learn more in code flow and graph analysis.
How SlicerCode does it: on load it parses the whole workspace with tree-sitter and builds call-, data-, and object-flow for every endpoint and job across 6+ languages, detecting external systems (Kafka, databases, HTTP, queues, caches) on each path. The agent pulls this via a get_flow_context tool, so it retrieves the actual flow it is about to change rather than similar-looking text. See flow determination on the features page.
Runtime-Grounded Context: What Actually Ran
Static analysis tells you what *could* happen; runtime data tells you what *did*. This gap matters most exactly where agents struggle: polymorphism and dynamic dispatch (which implementation of an interface actually executes), the real shape of a payload, the values a function returns for a given input. A static graph may show three possible implementations behind one call; a single traced run collapses that ambiguity to the one that ran.
Feeding an agent real observed values — concrete argument shapes, object state, and returns — is one of the highest-leverage forms of context you can supply. It replaces the model's guesses about data structures with ground truth, which sharply reduces the fabricated-fixture problem where a model invents a field that does not exist. Requirements checks benefit too: scoring an implementation against a spec is far more credible when it is computed from values the code actually produced.
How SlicerCode does it: it attaches to the VS Code debugger (DAP) to capture real arguments, object state, and a best-effort return at each step of a flow, with secrets and PII redacted before anything leaves the IDE. Those captures refine the static graph — resolving polymorphic edges to what ran — and feed the agent's get_runtime_values tool. The same observed values ground PRD validation, which scores a flow across code, executed flow, changes-still-to-make, and tests. See runtime analysis and dynamic tracing and the runtime feature.
Managing Tool Results: Pruning, Stubbing, and Compaction
In an agent loop, tool results are the fastest-growing part of the context. Every file read, search, and test run appends its output to the history, and a few verbose observations — a full file, a stack trace, a directory listing — can consume the budget on their own. Left unmanaged, these stale observations crowd out the material the agent needs for its next step, and the window fills with information that mattered ten steps ago and no longer does.
The core techniques are pruning and compaction. Stubbing replaces an old tool result with a short reference ("read LedgerService.java, 340 lines") once its content is no longer load-bearing, so the fact that it happened survives but the bulk does not. Pruning drops the oldest turns entirely once they fall outside a window of relevance. Compaction summarizes a long stretch of history into a compact digest when a task runs long. The guiding rule: keep the latest, highest-signal observations in full and shrink the rest.
How SlicerCode does it: old tool outputs are auto-stubbed and conversation history is pruned to keep each turn's prompt lean, which is a large part of why turns stay fast under a bounded budget. See token & context optimization in the docs.
- Stub — swap a stale, bulky result for a short reference to it
- Prune — drop turns that have fallen out of the relevance window
- Compact — summarize a long history into a durable digest
- Keep-latest — retain the most recent observations in full
Memory and Project Structure
Not everything an agent needs should be rediscovered each turn. There is a useful split between *ephemeral* context — the files and results relevant to the current step — and *durable* memory: stable facts about the project that are worth carrying across the whole session. The module layout, the build and test commands, the architectural conventions, the location of key services: re-reading dozens of files to relearn these on every turn is slow and wasteful. Persist them once as a compact digest and reference it on demand.
Rules files and a project-structure digest are how you encode this. A short, curated overview of the repository gives the agent project-wide orientation for a few hundred tokens instead of thousands of file reads, and a rules file steers *how* it should work — for instance, to consult the graph before editing. This is durable context engineering: shaping what the agent knows about your project before any single task begins.
How SlicerCode does it: it maintains a persistent .slicercode/structure.md repo digest for project-wide memory, and writes a .continue/rules/slicercode.md rules file that steers every turn — consult get_architecture and get_project_structure once per session, then get_flow_context for the specific flow being touched. That way the agent orients itself cheaply instead of re-reading the tree each time. Details are in the configuration docs.
The Cost and Latency of Context
Context is not free. Every token you place in the window is billed on input and processed on every step, so a bloated context multiplies both the bill and the wall-clock time across a long agent run. This is the economic case for tight context engineering: leaner prompts are not just more accurate, they are cheaper and faster. A budget that halves per-turn tokens roughly halves per-turn cost and latency.
Two mechanisms recover most of the waste. Prompt caching keeps a stable prompt prefix — system prompt, tools, rules — so repeated continuations reuse it at near-zero cost instead of reprocessing it every turn; this is why keeping the prefix stable matters. Response caching returns identical or near-duplicate requests without another model call at all. And task-aware routing sends trivial edits to a fast, cheap model and reserves a strong model for hard reasoning, so you are not paying frontier prices for boilerplate.
How SlicerCode does it: the backend keeps a stable prefix that always hits the upstream prompt cache, offers exact and semantic response caches (tenant-scoped, so nothing leaks across accounts), and routes each request to a weak or strong model by complexity — all on top of the bounded per-turn budget. See prompt caching and model routing in the docs.
- Prompt-prefix cache — reuse a stable system/tool prefix at near-zero cost
- Response cache — return identical or near-duplicate requests without a new call
- Task-aware routing — cheap model for easy work, strong model for hard reasoning
- Bounded budget — fewer tokens per turn cuts both cost and latency
Putting It Together: Context Engineering with SlicerCode
Good context engineering is a pipeline, not a single trick. Give the agent a bounded token budget; fill it with graph-precise code rather than fuzzy neighbors; ground it in real runtime values where they exist; carry durable project memory across turns; stub and prune tool results so recent signal wins; and cache the stable parts so it all stays cheap. Each layer compounds — precise retrieval keeps the budget small, a small budget keeps turns fast, caching keeps them affordable.
SlicerCode implements that pipeline end to end: a tree-sitter call/data/object graph across 6+ languages for structural context, DAP-captured runtime values to resolve what actually ran, a persistent project digest and rules for memory, auto-stubbing and history pruning for tool-result management, and a bounded per-turn budget backed by prompt/response caching and task-aware routing. The agent edits across files with accept/reject diffs and runs your build and tests — grounded in that context rather than guessing.
Explore the full feature set, read the configuration and settings docs, or install the VS Code extension to try it on your own repo. IntelliJ and a CLI are on the way — see the roadmap.
Frequently asked questions
What is context engineering for coding agents?
It is the practice of deciding what a coding agent sees at each step — which files, tools, prior results, and runtime facts enter the model's context window, and what is left out. Because an LLM can only reason over what is in its window, this selection largely determines the quality of the agent's edits.
How is context engineering different from prompt engineering?
Prompt engineering focuses on the wording of a single instruction; context engineering governs the entire working set around it — retrieved code, tool results, memory, and history — plus what to exclude. For agents, context engineering usually has a larger impact on accuracy than prompt phrasing.
Is a bigger context window always better for coding agents?
No. Larger windows raise cost and latency on every step and suffer from context rot and the 'lost in the middle' effect, where buried facts are attended to less reliably. Precise, high-signal context under a token budget usually beats filling a large window.
Should I use RAG or a code graph to give an agent context?
Embeddings/RAG work well for fuzzy, natural-language lookups like documentation, but they split functions from callers and retrieve by similarity rather than structure. For editing code, a call/data-flow graph retrieves along real relationships and is the higher-signal source; the two are complementary.
How do you keep tool results from filling up the context window?
Stub stale, bulky results down to a short reference, prune old turns once they fall out of relevance, and compact long histories into a digest — while keeping the most recent observations in full. SlicerCode auto-stubs old tool outputs and prunes history to keep each turn's prompt lean.
How does SlicerCode manage context for its coding agent?
It grounds the agent in a tree-sitter call/data/object graph and real DAP-captured runtime values, carries a persistent project digest and rules for memory, auto-stubs and prunes tool results, and runs under a bounded per-turn token budget with prompt/response caching and task-aware model routing.
Keep learning
See it in your codebase
SlicerCode brings the agent, flow graphs, runtime capture, PRD validation and test generation into VS Code.