Skip to content

MustafaKucukcoskun/Refine-agent-kit / .agents/skills/context-engineering

context-engineering

Verified

Context Engineering

Production-grade patterns for managing AI agent context windows effectively. Aligned with Anthropic's "Effective Context Engineering" (2025-2026) β€” context engineering > prompt engineering.

When to Use vs. Related Skills

You want to…Use
Plan overall context strategycontext-engineering (this)
Route agent tasks based on intentintelligent-routing
Coordinate parallel agentsparallel-agents
Pick behavioral modebehavioral-modes
Debug agent confusionsystematic-debugging

Core Principle

Context is your agent's most precious resource. Every token matters. A well-engineered context window is the difference between a brilliant agent and a confused one.


1. Context Window Management

The Context Budget Rule

Before ANY complex task, calculate your budget:

Total Context = System Prompt + Rules + Agent + Skills + MCP Tools + Conversation + Working Memory
LayerTypical LoadControl
System prompt~2K tokensFixed
Rules (GEMINI.md)~3-6K tokensFixed (always_on)
Agent file~3-26K tokensPer-request
Skill files~10-113K tokensJIT loaded
MCP tool definitions~1-4K per serverPer-config
Conversation historyGrowingManaged by IDE
Working memoryVariableYour control

Budget Thresholds

Total UsageStatusAction
< 50K🟒 ComfortableNormal operation
50-100K🟑 CautionAvoid loading large skills simultaneously
100-150KπŸ”΄ DangerSummarize, offload, prioritize
> 150Kβ›” CriticalContext collapse imminent β€” reduce immediately

2. Progressive Disclosure Strategy

JIT (Just-In-Time) Loading

Don't load everything at once. Load resources only when needed:

Level 0: Rules (always loaded) ←────── ~6K tokens
Level 1: Agent persona (on request) ← ~3-26K tokens
Level 2: Skill SKILL.md (on demand) ← ~2-10K tokens
Level 3: Skill sub-files (deep dive) ← Variable
Level 4: MCP tool results (runtime) ← Variable

Decision Tree

User request arrives
β”œβ”€β”€ Simple question? β†’ Level 0 only (no agent/skill needed)
β”œβ”€β”€ Single-domain task? β†’ Level 0 + 1 agent + 1-2 skills
β”œβ”€β”€ Multi-domain task? β†’ Level 0 + orchestrator + targeted skills
└── Deep research? β†’ Progressive: start Level 2, expand to Level 3 as needed

Anti-Pattern: The Kitchen Sink

❌ WRONG: Load 5 agents + 10 skills + all MCP tools = 200K+ tokens
βœ… RIGHT: Load 1 agent + 2 skills + targeted MCP = 30K tokens

3. Skill Loading Strategy

Index-First Pattern

  1. Read SKILL.md header (frontmatter) β€” ~200 tokens
  2. Scan section headings β€” ~100 tokens
  3. Read ONLY the section matching the user's request
  4. Load sub-files/references ONLY if the section refers to them

Skill Size Awareness

Skill SizeStrategy
Small (< 5KB)Load fully, no concern
Medium (5-30KB)Load SKILL.md, sub-files JIT
Large (30-100KB)Load SKILL.md header + relevant section only
XL (> 100KB)⚠️ Never load fully. Summary + targeted sections

Concurrent Skill Limit

Rule: Maximum 3 skills actively loaded at once.

If you need more:

  1. Summarize current skill insights β†’ working memory
  2. Unload (stop referencing) the completed skill
  3. Load the next skill

4. Multi-Agent Context Sharing

The Handoff Pattern

When orchestrator delegates to specialist agents:

Orchestrator Context:
β”œβ”€β”€ Task summary (< 500 tokens)
β”œβ”€β”€ Key constraints
β”œβ”€β”€ Expected output format
└── DO NOT pass: full conversation history, all skills, all MCP results

Context Isolation

Each agent should receive ONLY:

  • Its own persona file
  • Relevant skill(s) for the sub-task
  • Task-specific context (not everything)
  • Clear exit criteria

Anti-Pattern: Context Flooding

❌ WRONG: Pass entire conversation + all research to sub-agent
βœ… RIGHT: Summarize β†’ extract key points β†’ pass structured brief

5. Token Budget Optimization Techniques

Summarization Checkpoints

After every 5-10 tool calls, create a mental checkpoint:

What I've learned:    [key findings, 3-5 bullets]
What I still need:    [remaining questions]
Current approach:     [1-sentence strategy]

File Reading Strategy

File SizeStrategy
< 100 linesRead fully
100-500 linesRead outline first, then targeted sections
> 500 linesSearch (grep) first, read only matching regions

MCP Tool Result Management

  • context7: Results can be large. Extract key code snippets, discard boilerplate.
  • Playwright: Snapshots are large. Use targeted element snapshots, not full-page.
  • Serena: Symbol results are structured. Focus on signatures, not implementations.

6. Context Recovery Patterns

When Context is Lost (Long Sessions)

  1. Re-read task.md or implementation_plan.md (your own artifacts)
  2. Check Knowledge Items (KIs) for distilled past insights
  3. Re-read only the 1-2 most critical source files
  4. DON'T re-read everything β€” targeted recovery only

Session Continuity

Between sessions, ensure:

  • Key decisions are written to artifacts (not just in conversation)
  • Open questions are explicitly listed
  • Next steps are documented in task.md

7. System Prompt Engineering

Effective Rule Writing

PrincipleExample
Be specific"Max 40 lines per function" > "Keep functions short"
Use tablesStructured data loads faster than paragraphs
Avoid repetitionSay it once, reference it elsewhere
Priority markersπŸ”΄ critical > 🟑 important > 🟒 nice-to-have

Rule Size Budget

CategoryTarget SizeJustification
Global rules< 8K tokensAlways loaded, must be lean
Agent persona< 10K tokensLoaded per-request
Skill SKILL.md< 5K tokensIndex file, not the full skill

Quick Reference Checklist

Before starting any complex task:

  • Estimate total context load (rules + agent + skills + MCP)
  • Is it under 100K? If not, reduce
  • Am I loading only what I need? (JIT, not everything)
  • Do I have a summarization checkpoint plan?
  • Are my artifacts capturing key decisions?

Remember: A lean context window produces better results than a bloated one. When in doubt, summarize and discard β€” you can always re-read.


Structured Note-Taking Pattern (_memory/NOTES.md)

For long-horizon tasks, maintain a persistent scratchpad the agent reads on every turn:

# NOTES.md β€” <task name>

## Goal
<one-sentence outcome>

## Current State
- Phase: 3 of 5 (Implementation)
- Branch: feat/auth-rewrite
- Last verified: 2026-04-20 14:30

## Decisions Made
- DB: PostgreSQL 16 (not MySQL) β€” reason: JSONB support
- Auth: JWT + refresh token rotation β€” reason: mobile client planned
- Stack: FastAPI 0.115 + SQLAlchemy 2.0 async

## Open Questions
- [ ] How should we handle token revocation? (blocking: need answer before phase 4)
- [ ] Rate limiting per user or per IP? (soft, can decide later)

## Done
- [x] Schema designed (`docs/schema.md`)
- [x] OAuth flow implemented
- [x] Tests for happy path

## Next
- [ ] Error path tests
- [ ] Rate limit middleware
- [ ] Docs update

Rules:

  • Append-only for Decisions Made (never rewrite history)
  • Move items between Open Questions / Done / Next as state changes
  • At each long-run checkpoint, the agent re-reads this file
  • Keep it < 500 lines β€” summarize older sections if it grows

Compaction Protocol (when approaching limit)

When context fills to ~70%:

  1. Stop current reasoning chain
  2. Write summary to _memory/NOTES.md β€” decisions, next steps, blockers
  3. Discard verbose tool outputs (keep summaries only)
  4. Resume with compacted context

When context fills to ~85%:

  1. Same as 70% but stricter β€” drop all tool outputs older than 3 turns
  2. Keep only: system prompt, NOTES.md, last user message, last 2 assistant turns

Sub-Agent Contract

When delegating to a sub-agent via _handoff/:

  • Sub-agent works in isolated context
  • Returns 1000-2000 token summary in _handoff/<name>/output.md
  • Raw data (full files, diffs) goes in _handoff/<name>/artifacts/
  • Main agent reads only the summary on return

Anti-Patterns

Anti-patternImpactFix
Dumping full file contentsContext bloatReference by path, load JIT
Keeping all tool outputsToken wasteDiscard after synthesis
Re-reading NOTES.md every turn unchangedNo-op tokensOnly re-read after external change
Loading 10+ skills "just in case"Pollutes reasoningProgressive disclosure
No summarization planContext cliff at limitPlan compaction checkpoint at start
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 196kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 192kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 192kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 192kUpdated Claude CodeCodexVerifiedInstall