Prompting & Context Management for Coding Agents
- Explain what consumes a coding agent's context window and why quality drops as it fills
- Write a coding prompt with goal, constraints, references, a pattern to follow and a verifiable done criterion
- Apply clarify-first, plan-first, small-task and feedback-loop patterns to Go work
- Keep sessions healthy with clearing, compaction, subagents, durable notes and worktrees — and know when to restart
- Keep customer data out of prompts in a bank or e-commerce codebase
TL;DR
- Context is the scarce resource. System prompt, instruction files, files read, tool output and conversation share one window, and quality degrades as it fills. Spend it deliberately.
- A good coding prompt has five parts: goal, constraints, references, an existing pattern to follow, and a done criterion the agent can check — "done when
go test ./internal/refund/... -racepasses and lint shows no new warnings". - Clarify, then plan, then code. Ask the agent to question you and propose a plan before touching files; skip this only when the diff fits in one sentence.
- Give it a fast feedback loop: targeted tests that run in seconds, not the 20-minute suite on every step.
- Hygiene beats heroics: clear between unrelated tasks, delegate exploration to subagents, keep durable notes in files, and after two failed corrections restart with a better prompt.
- Parallelise with git worktrees, one agent per worktree — your review bandwidth is the real limit.
- Never paste production customer data into a prompt: no account numbers, ID numbers, card numbers or raw production logs.
Why it matters
Two engineers with the same model and repo get very different results, and the difference is almost always context: what they put in, what they kept out, and whether the agent could check its own work. In a bank, a muddled session ends with an agent "simplifying" an idempotency check because a test was hard to satisfy. During a flash-sale incident, a clean prompt with a reproduction test gets a fix in minutes while a kitchen-sink session flails.
Context discipline is also governance: what enters the window leaves your laptop for a model provider unless you self-host, so prompt hygiene is data-protection hygiene.
Core concepts
Context is the scarce resource
Everything the agent knows in a session lives in one context window, re-read on every step:
| Source | Rough size (≈, varies) | How you control it |
|---|---|---|
| System prompt, tool and MCP definitions | Thousands to tens of thousands of tokens | Enable only the MCP servers you need |
| Instruction files | Hundreds to thousands | Keep them short; move rarely needed detail into referenced docs |
| A 500-line Go file | ≈ 4–6K tokens | Point at the right files instead of "look around" |
| Verbose test or build output | Can reach tens of thousands | Run targeted tests; filter output |
| Conversation and failed attempts | Grows every turn | Clear, compact, restart |
Long-context degradation is real (LLM Fundamentals for Engineers): as the window fills, agents forget earlier instructions, repeat failed fixes and contradict decisions. Anthropic's Claude Code guidance builds most of its advice on that constraint. As of 2026, Claude Code shows usage with /context; other agents have equivalents — check current docs.
Anatomy of a coding prompt
| Part | Purpose | Example |
|---|---|---|
| Goal | What and why | "Support partial refunds: several refunds until the captured amount is used up" |
| Constraints | What must not change | "int64 minor units; no new dependencies; gRPC contract unchanged except the new RPC" |
| References | Where to look | Files, ADR, ticket (redacted) |
| Pattern to follow | Steer style and structure | "Mirror internal/capture/partial.go" |
| Done criterion | Something the agent can run | "go test ./internal/refund/... -race passes; no new lint warnings; show me the output" |
A complete example:
Goal: add partial refunds to the refund service. A merchant can refund part of
a captured payment, several times, until the captured amount is used up.
Constraints:
- Amounts are int64 in minor units (VND has none, so 1 = 1 dong). No float64.
- Do not change the public gRPC contract except adding the new RPC.
- Reuse the existing idempotency middleware; every refund needs an Idempotency-Key.
- No new dependencies.
References:
- internal/refund/service.go (current full-refund flow)
- docs/adr/0012-refund-ledger-postings.md
- Ticket PAY-1432 (pasted below, customer data removed)
Pattern to follow: internal/capture/partial.go (validation and ledger posting style).
Done when:
- go test ./internal/refund/... -race passes, including table-driven tests for
refund > remaining, concurrent refunds on one payment, and a duplicate key.
- golangci-lint run ./internal/refund/... shows no new warnings.
- You show me the test output and a short summary of the diff.
Before coding, ask me any clarifying questions, then propose a plan.
The constraints encode exactly what agents get wrong — money types, contracts, idempotency — and the done criterion turns "looks finished" into a check. See Requirements → Spec → Plan with AI for producing the spec this prompt refers to.
Patterns that work
- Clarify first. "Ask me clarifying questions before writing code" surfaces ambiguities ("can a refund exceed the original if a fee was added?") while they are cheap. For larger features, let the agent interview you and write the answers into a spec file.
- Plan first. Have the agent read the relevant code and propose a plan before editing — as of 2026, Claude Code's plan mode (Shift+Tab, or
--permission-mode plan) forbids edits until you approve. Review the plan as you would a design doc; editing a plan is cheaper than reverting code. Skip it for one-sentence diffs. - Small tasks. One concern per session; vertical slices; commit after each green step so a bad step is a cheap
git reset. - Point at a pattern. "Follow
internal/capture/partial.go" beats paragraphs of style rules and keeps a large codebase consistent. - Give it a feedback loop. Name the exact command:
go test ./internal/refund/ -run TestPartialRefund -race. For bugs, ask for a failing test first, then the fix. Encode money invariants as tests so the agent can check them. - Ask for evidence, not assertions. "Paste the test output" is faster to review than re-running everything yourself.
- Use a fresh context to review. A second session or subagent that sees only the diff and the requirements is less biased toward the code it just wrote; ask for gaps, not compliments.
Context hygiene
- Clear between unrelated tasks. As of 2026,
/clearin Claude Code; a new session elsewhere. - Compaction is lossy. Automatic or manual (
/compactwith a focus, such as "keep the list of modified files and the failing test names") summarises history to free space, and exact error messages and small decisions can vanish. Prefer clearing plus notes when switching phases. - Subagents for exploration. "Use a subagent to find every place we compute fees" — the subagent reads dozens of files in its own context and returns a summary, so your main context stays focused on implementation.
- Durable notes live in files, not chat. Keep
PLAN.md(checklist of steps, ticked as completed) andNOTES.md(decisions, gotchas, commands that worked). They survive clearing, compaction, a new session and a hand-off to a teammate. Decide per team whether they are committed or git-ignored. - Rewind instead of arguing. As of 2026, Claude Code checkpoints each turn and can restore conversation and code (
/rewind, or Esc twice). Checkpoints do not cover shell side effects and are not a substitute for git. - Restart rather than correct a derailed session. Signs: the same fix tried twice, edits to unrelated files, tests weakened or skipped, features "simplified" away, earlier decisions contradicted. Anthropic's guidance is blunt: after two failed corrections, clear and start again with a better prompt.
Parallel work with git worktrees
A worktree is a second checkout of the same repository on its own branch, so two agents never edit the same files:
git worktree add ../payments-partial-refund -b feat/partial-refund
git worktree add ../payments-fee-rounding -b fix/fee-rounding
cd ../payments-partial-refund && claude # or any agent; one session per worktree
git worktree list
git worktree remove ../payments-fee-rounding
As of 2026, Claude Code can create one for you with claude --worktree <name> — check current docs. Watch for shared resources the checkouts still collide on: local ports, Docker Compose project names, a shared local database schema, generated files. The bottleneck is not the agents but you: every parallel stream produces a diff someone must review properly, so a small number of streams is usually the practical ceiling.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Keep going in the same session | History is valuable; no re-explaining | Context fills; failed attempts linger | Deep in one problem and still on track |
| Compact with a focus | Frees space, keeps a summary | Lossy; exact details disappear | One long task nearing the limit |
| Clear + notes file | Clean context, durable learnings | You must write good notes | Switching tasks; after repeated failed corrections |
| Subagent exploration | Main context stays clean | Summary may omit details; extra tokens | Wide searches, codebase questions, reviews |
| New worktree session | File and branch isolation | Merge and review load | Independent tasks in parallel |
| Rewind to a checkpoint | Cleanly undoes a bad turn | Misses shell side effects; not git | The agent took a wrong turn recently |
In practice
Prompt library for Go work
Adapt these and keep them in the repo (for example as reusable commands or skills — see Setting Up a Repo for AI Agents).
Table-driven tests
Write table-driven tests for ParseAmount in internal/money/parse.go.
Follow the style of internal/money/format_test.go (t.Run subtests, no testify).
Cover: valid VND and USD inputs, empty string, negative values, overflow beyond
int64, separators "1.000.000" and "1,000,000", and non-numeric input.
Do not change parse.go. If a test fails because of a real bug, stop and tell me;
never change an expectation to make a test pass.
Done when: go test ./internal/money/ -run TestParseAmount -race passes, or you
have reported the failing cases with your diagnosis.
Refactor safely
Refactor internal/order/checkout.go: extract inventory reservation behind a
Reserver interface so it can be faked in tests. Behaviour must not change.
1) Run go test ./internal/order/... and record the baseline.
2) Change in small steps; rerun the tests after each step and commit when green.
Do not rename exported symbols outside internal/order. Do not touch pricing code.
Done when: tests pass at every step, go vet is clean, and you list anything you
were unsure about.
Debug with hypotheses
Bug: about 1 in 500 transfer requests fails with "deadlock detected" under load.
Redacted logs for three failures are in tmp/deadlock.log.
Do not change code yet. First:
1) read internal/transfer/repo.go and the log;
2) list up to three hypotheses ranked by likelihood, with evidence for each;
3) propose a test or script that would confirm or reject the top hypothesis.
Wait for my go-ahead. The fix must include a regression test that fails before
the change and passes after.
Explain unfamiliar code
Explain how settlement batching works in internal/settlement/. I am new here.
Use a subagent to explore so this session stays focused.
Give me: entry points, data flow from ledger entries to the settlement file,
where state is persisted, what runs concurrently, and anything that looks risky
or dead. Cite file:line for every claim. Do not edit anything.
Write a migration
Add a nullable column refunded_amount BIGINT to payments, following
docs/migrations.md (expand/contract) and the style of
migrations/0041_add_capture_ref.sql. The table has about 80M rows and serves
live traffic: no table rewrite, no long locks, set lock_timeout, and backfill in
batches of 10k from a separate job, not inside the migration.
Produce: up and down SQL, the backfill job, and a rollout checklist.
Done when: make migrate-test passes against the local Postgres container and you
have explained which lock each statement takes.
The migration prompt leans on Zero-Downtime Schema Migrations; the test prompts on Testing & Benchmarking and TDD & Testing with AI.
Keep customer data out of the context
- Never paste production customer data — account numbers, citizen ID (CCCD) numbers, card numbers, phone numbers, addresses, transaction histories — into a prompt, even "just to debug". It leaves your control, may be retained, and card data in the context puts the tool in PCI DSS scope.
- Use synthetic fixtures that reproduce the bug's shape: the same currency, amount edge case and state transition, with fake identities.
- Redact logs before sharing with a script, not by eye; save them to a file and let the agent grep it rather than pasting thousands of lines.
- Keep secrets unreadable: deny agent reads of
.envand credential files; never give an agent production credentials. - Sanctioned access only: if agents must query logs or data, do it through an approved, redacting, read-only tool or MCP server that security has reviewed (LLM Security, Privacy & Governance).
Common pitfalls
- Kitchen-sink sessions. Feature work, then an unrelated question, then back again; the agent mixes up requirements from both. Clear between tasks.
- Pasting a 5,000-line log. It floods the window and pushes your instructions into the forgotten middle. Save it to a file, grep for the relevant window, or let a subagent summarise.
- Vague asks. "Make it better" yields churn across files you did not want touched. State the goal, scope and done criterion.
- Running the 20-minute suite every step. Iterations crawl and output floods context. Use targeted tests per step and the full suite at the end or in CI.
- Accepting without reading. The diff compiles and tests pass, but a test was weakened or an authz check removed. Read every line of money and security code (Reviewing AI Code & CI Guardrails).
- Bloated instruction files. A thousand-line
CLAUDE.mdcosts tokens every session and buries the rules that matter. - Asking "is this correct?" Preference-tuned models lean toward yes; ask for the three most likely bugs instead.
Interview angle
- "How do you make AI-generated code trustworthy?" — prompts with explicit constraints and runnable done criteria, plan review, small diffs, tests encoding invariants, CI gates, human review of money and security paths.
- "How would you standardise AI usage across 20 teams?" — shared prompt library and instruction files in each repo, data-handling rules, review norms, and metrics on outcomes rather than usage (Big Tech Practices & Team Adoption).
- Treating context as a budget, with concrete hygiene practices, signals hands-on experience. Red flags: "I let it run until it says done"; pasting production data "because it's internal".
Self-check
1. What fills a coding agent's context, and which parts do you control?
System prompt and tool definitions (fixed by the harness, partly controllable by enabling fewer MCP servers), instruction files (you keep them short), files read (you point at the right ones), tool output (you choose targeted commands and filter output), and the conversation itself (you clear, compact or restart).
2. Turn "fix the refund bug" into a good prompt. What must it contain?
The symptom and how to reproduce it, the likely location, constraints (money types, contracts that must not change, no new dependencies), the existing pattern to follow, and a done criterion: a failing regression test first, then the fix, with the exact test command passing and the output shown.
3. When should you restart a session instead of correcting it?
When you have corrected the same issue twice without success, or you see derailment signs: repeated fixes, edits to unrelated files, weakened tests, removed features, contradicted decisions. Save learnings to a notes file, clear, and re-prompt with the constraints you discovered.
4. Why delegate exploration to a subagent?
Exploration reads many files, most irrelevant to the final change. A subagent does that reading in its own context and returns a summary, so the main session keeps a lean context focused on implementation — and its quality holds up for longer.
5. Your full test suite takes 20 minutes. How do you give the agent a useful feedback loop?
Give it targeted commands for the packages and tests it touches (go test ./internal/refund/ -run TestPartial -race), plus go vet and lint on changed packages; add a fast reproduction test for bugs. Run the full suite once at the end, or let CI run it.
6. A teammate pasted production logs with customer phone numbers into a prompt. What is wrong, and what process fixes it?
Personal data left the bank's control for a third party, possibly retained and outside the approved data flows — a data-protection incident, not a style issue. Fix: report it per policy, then provide a redaction script and synthetic fixtures, deny agent access to raw production logs, and offer a sanctioned redacting log tool.
Exercise
Run the same Go task twice and compare:
- Pick a real, non-sensitive change (for example, partial refunds in a toy payments service from Walkthrough: Refund API from Requirement to Production).
- Run A: a one-line prompt in a session already used for something else; accept corrections as they come.
- Run B: a fresh session, the five-part prompt, clarifying questions, an approved plan saved to
PLAN.md, targeted test commands, and a subagent review of the final diff. - For both, record corrections needed, context used at the end (for example via
/context), wall-clock time, and defects you find on review. - Save the Run B prompt as a reusable template in the repo.
Done when: you have a short comparison table, a committed prompt template, and one paragraph on which hygiene practice made the biggest difference.
Further reading
- Anthropic, Claude Code documentation: "Best practices" and "Common workflows" — check current docs; features change often.
- Anthropic, "Effective context engineering for AI agents" (engineering blog, 2025).
- Liu et al., "Lost in the Middle: How Language Models Use Long Contexts" (2023).
- Chroma, "Context Rot: How Increasing Input Tokens Impacts LLM Performance" (2025).
- Git documentation:
git-worktree. - The
AGENTS.mdopen format (agents.md).
Related
- AI Coding Tools & How Coding Agents Work — the loop this page teaches you to drive.
- Setting Up a Repo for AI Agents — instruction files, commands, hooks.
- Requirements → Spec → Plan with AI — where the prompt's references come from.
- TDD & Testing with AI — building the feedback loop.
- Reviewing AI Code & CI Guardrails — what to check before merging.
- LLM Fundamentals for Engineers — why long contexts degrade.
- Zero-Downtime Schema Migrations — the rules behind the migration prompt.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).