agentleFS
anderson-c-santosanderson-c-santos/claude-skills-network/skills/context-engineering/SKILL.md

context-engineering

Skill1 starsChanged 5 months agoMITView on GitHub

Use this skill when building AI agents, multi-agent systems, Claude Code tools, or optimizing LLM context — context window mechanics, KV cache strategy, compression techniques, degradation patterns, memory system design (Mem0/Zep/Letta), tool design principles, harness engineering for autonomous loops, and LLM evaluation methodology. Activate for any agent architecture, MCP server design, or AI system engineering task.

82 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use using-agent-skills, constraint-driven-development and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • LLl0k0laDSkill

    using-agent-skills

    Use when starting a session or when you need to discover which skill applies to the current task. This is the meta-skill that governs how all other skills are discovered and invoked.

    Also in 24 projects that use this

  • vinvcnSkill

    constraint-driven-development

    把一个项目的质量线确立为书面契约,并阻止 agent 悄悄降低它。通过访谈确定用户在意哪些维度,当用户心里没有数字时提供合理的默认阈值,把一切记录进 CONSTRAINTS.md,并盯住 diff 中质量线被削弱的迹象——新增的 @ts-ignore 或 eslint-disable 抑制注释、被跳过或删除的测试、被剥掉的断言、未实现的 stub、被调低的阈值。当没有任何质量线被写下来时使用;当用户说 "set up constraints" 或 "define our standards" 时;当用户希望把他们在意的维度——无障碍性、Web 性能、覆盖率——设置成被强制执行的约束时;当 agent 为了变绿不断静默检查或跳过测试时;当你需要一个覆盖率或性能阈值却不知道该选什么数字时;或者当 agent 写下的代码超出任何人会读的体量时。

    Also in 4 projects that use this

  • LLl0k0laDSkill

    shipping-and-launch

    Use when preparing to deploy to production. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy.

    Also in 26 projects that use this

  • galandoSkill

    source-driven-development

    Version-aware, source-driven development — fetch official docs before writing framework code

    Also in 25 projects that use this

  • az9713Skill

    deprecation-and-migration

    Manages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when deciding whether to maintain or sunset existing code.

    Also in 22 projects that use this

  • +7 more from LLl0k0laD

The file

We split this skill into the rules it gives an agent

9 rules. 0 are common, 9 are distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 77 edited versions we read keep these.

  • 9

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Put stable content at the top.

    line 46
  2. Distinctive:

    When a tool returns large output, store it and load a reference:

    line 65
  3. Distinctive:

    Keep instructions and outcomes.

    line 82
  4. Distinctive:

    Not the full orchestrator trajectory.

    line 128
  5. Distinctive:

    Latent briefing / KV cache sharing: instead of re-transmitting full context to workers as text, share the KV cache representation filtered …

    line 130
  6. Distinctive:

    Never let an agent modify its own evaluation criteria.

    line 165
  7. Distinctive:

    Novelty gate: before acting, check if this exact change was tried before (rejection/revision ledger).

    line 173
  8. Distinctive:

    Single vs multi-agent: start single. Add agents only when context isolation is genuinely needed, not as an architectural preference.

    line 216
  9. Distinctive:

    Always estimate before building.

    line 222

“Common” is measured: kept by at least 6 in 10 of the 77 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Context Engineering

Context Window Fundamentals

Context = complete state at inference time:

System prompt + Tool definitions + Retrieved documents + Message history + Tool outputs

Optimization target: tokens-per-TASK (total across the task), NOT tokens-per-request. Aggressive compression that forces re-fetching costs more overall.

U-shaped attention curve: models attend strongly to the beginning (system prompt) and end (recent messages). Middle degrades. Critical facts buried in the middle get ignored. Design context so:

  • System prompt = stable instructions + role + constraints
  • Recent messages = current task state
  • Middle = historical context (summarize aggressively)

Quality > quantity: 10k tokens of high-signal context beats 100k tokens of noise. Noise crowds out attention budget and diffuses focus.

Context Degradation Patterns

PatternSignalMitigation
Lost-in-middleModel ignores facts stated mid-contextMove critical info to top or bottom
PoisoningContradictory info corrupts reasoningValidate and deduplicate before loading
DistractionOff-topic context pulls attention wrongScope retrieval tightly to current subtask
ConfusionSimilar but distinct concepts mergedExplicit labeling and clear separation
ClashTwo valid but conflicting instructionsExplicit priority ordering in system prompt

Treat degradation as an engineering problem — it has measurable thresholds, not random failure.

KV Cache Strategy

Cache hit = near-zero cost to re-process identical prefix tokens.

Structure for maximum cache efficiency:

[STABLE, CACHED]    ← system prompt, tool definitions, long reference docs
[VARIABLE, FRESH]   ← conversation history, current task context

Put stable content at the top; variable content at the bottom. Any change to cached prefix invalidates all subsequent cache entries.

Anthropic prompt cache: prefix up to 50k tokens. Cache TTL ~5 min. Savings: ~90% on cached input tokens.

# Enable caching on system prompt (Anthropic SDK)
{
    "role": "system",
    "content": [{
        "type": "text",
        "text": "...long stable instructions...",
        "cache_control": {"type": "ephemeral"}
    }]
}

Context Compression Techniques

Tier 1 — Observation masking: When a tool returns large output, store it and load a reference:

# Instead of putting 5000-token tool output in context:
result = run_tool()
save_to_file("result.json", result)
return "Result saved to result.json. Key finding: X"

Tier 2 — Structured summarization:

decisions: [list of irreversible choices made]
files_modified: [paths + what changed]
open_risks: [things that could go wrong]
next_actions: [concrete next steps]

Tier 3 — Selective retention: Keep instructions and outcomes. Drop step-by-step reasoning from history.

Budget trigger: define a threshold (e.g., >80% context used) → automatically compact before exhaustion, not after.

Memory System Design

4 memory types:

TypeStorageScopeExample
In-context (working)Token windowCurrent sessionConversation history
External semanticVector/graph DBCross-sessionUser facts, project state
EpisodicSummariesPast sessions"Last week we deployed X"
ProceduralFiles/promptsPersistentSkill files, CLAUDE.md

Framework selection:

  • Mem0 — vector store, fast semantic retrieval. No graph structure. Good for simple "remember user facts."
  • Zep/Graphiti — temporal knowledge graph, entity tracking over time. Good for "what changed about X."
  • Letta — structured in-context + archival + recall layers. Good for complex stateful agents.

Temporal validity: memories expire. Tag with creation timestamp + TTL. Stale confident memories are worse than no memory. Always verify memory against current file state before acting on it.

Multi-Agent Patterns

Primary reason for sub-agents: context isolation, not role-playing. Each agent has its own clean window.

When to use sub-agents:

  • Task decomposes into genuinely parallel, independent subtasks.
  • Different subtasks need different tool sets or system prompts.
  • Single agent context window is the actual bottleneck.

Coordination patterns:

PatternWhen to use
Supervisor/workerOrchestrator delegates, workers return structured results, orchestrator synthesizes
SwarmPeer agents with shared goal, emergent coordination
PipelineSequential agents, each transforms previous output

Handoff discipline: workers need exactly:

1. Task description (what to do)
2. Relevant context slice (just what they need)
3. Expected output format (schema)

Not the full orchestrator trajectory. Over-sharing wastes tokens and confuses the worker.

Latent briefing / KV cache sharing: instead of re-transmitting full context to workers as text, share the KV cache representation filtered to what the worker needs. Reduces worker input cost without summarization loss.

Tool Design Principles

Tool description is the contract. The model generates calls from description alone.

Trigger-focused descriptions:

Bad:  "Gets user data"
Good: "Retrieve a user's profile when you need their email, name, or account status"

Schema design rules:

  • Required params: only for what's always needed.
  • Optional params: for configuration/overrides.
  • Enums for constrained choices (never free-string where enum works).
  • Description on every param, not just the tool name.

Actionable error messages:

Bad:  "Invalid input"
Good: "Parameter `date` must be ISO 8601 format (e.g. 2026-06-29). Received: '29/06/2026'"

Tool catalog hygiene: >10 tools with overlapping purposes → model picks wrong half the time. Consolidate. Use verb-noun naming: search_documents, create_task, update_user.

MCP namespacing: server_name__tool_name convention prevents collision across servers.

Harness Engineering (Autonomous Loops)

Harness = control system around agent: what it may edit, how it gets feedback, where state lives, how failures recover, who approves irreversible actions.

Locked vs editable surfaces:

  • Metrics/rubrics = LOCKED (agent must not weaken its own evaluation criteria).
  • Code/content = editable.
  • Never let an agent modify its own evaluation criteria.

State machine for long runs:

initialized → retrieved → evaluated → proposed → validated → done

Each transition is logged. Never hand-edit state files mid-run.

Novelty gate: before acting, check if this exact change was tried before (rejection/revision ledger). Prevents re-discovering failed paths on loop iteration 12.

Human approval boundary: irreversible actions (push to prod, send email, delete data) require explicit approval each time. Authorization for one instance ≠ authorization for all instances.

Durable logs: append-only. Every decision, every output, every failure. Required for audit and rollback.

LLM Evaluation Methodology

Evaluation pipeline order:

  1. Deterministic checks (syntax, format, schema) — fast, cheap, no model needed.
  2. Heuristic checks (length, keyword presence) — fast rules.
  3. LLM-as-judge — only where deterministic checks can't reach.

LLM-as-judge bias mitigation:

  • Position bias: randomize option order when comparing.
  • Verbosity bias: normalize length before judging (longer ≠ better).
  • Self-enhancement: don't use the same model to judge its own output.
  • Calibrate rubrics with human baselines before trusting judge scores.

Pairwise > absolute scoring: "A or B?" is more reliable than "score 1-10."

Required evaluation dimensions:

  • Correctness — is it factually right?
  • Completeness — does it cover all required aspects?
  • Grounding — no hallucination of sources/quotes?
  • Format compliance — matches required schema/structure?
  • Safety — no harmful output?

Regression suites: golden examples locked before any change. Accuracy is a misleading aggregate — look at per-task effect sizes and confusion matrix.

Task-Model Fit

LLMs are the right tool when:

  • Output is natural language or structured text.
  • Quality can be judged by a model or human (not exact computation).
  • Failure is recoverable (not irreversible operations at scale).
  • Cost per call is acceptable for the task volume.

LLMs are wrong when:

  • Exact computation required (use code).
  • Latency < 100ms required (LLMs are too slow).
  • Output must be perfectly deterministic (use deterministic algorithms).

Single vs multi-agent: start single. Add agents only when context isolation is genuinely needed, not as an architectural preference.

Cost Optimization

Cost = token_count × calls × (input_price + output_price)

Always estimate before building. At scale, compression and caching change economics dramatically.

High-ROI optimizations:

  1. KV cache for stable system prompt (90% savings on repeated prefix).
  2. Prompt compression (remove verbose examples, use concise instructions).
  3. Model right-sizing (Haiku for classification/routing, Sonnet for generation, Opus for complex reasoning).
  4. Batch API for offline workloads (50% discount, async delivery).
  5. Output length control (set max_tokens tight; verbose output = expensive).

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.