agentleFS
Gzyms69Gzyms69/agent-setup-bundle/skills/skill-context-engineering/SKILL.md

skill-context-engineering

Skill0 starsChanged 3 months agoMITView on GitHub

Production context engineering, attention budget curation, Anchored Iterative Summarization, Artifact Trail Tracking, tokens-per-task optimization, and MemPalace context compaction. MUST ACTIVATE for long-running sessions, multi-step refactors, high token load, or when diagnosing attention degradation (lost-in-the-middle, context poisoning).

The file

We split this skill into the rules it gives an agent

7 rules. About 0 are common, 4 are distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈4

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Do NOT activate for:

    line 24
  2. Distinctive:

    When compressing long conversation histories, avoid freeform summaries that silently discard critical identifiers.

    line 54
  3. Very specific:

    1-Line Atomic Tombstones: Keep historical awareness without attention pollution by recording a single line in the decision log: - [PRUNED …

    line 92
  4. Very specific:

    Scratchpad Archiving: If an abandoned design is large (>50 lines), offload it to <appDataDir>/brain/<id>/scratch/archived_<feature>.md …

    line 94
  5. Distinctive:

    Preserve Specific Identifiers: Always preserve exact file paths, exported symbol names, error codes, and line numbers across compression …

    line 102
  6. Distinctive:

    When an invalid assumption or tool hallucination enters context, it compounds through self-reference.

    line 108
  7. Very specific:

    Re-anchoring: Do NOT stack multiple conversational retries.

    line 110

≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “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 Skill

Context engineering is the science of curating the language model's attention window. As conversational trajectories grow, models exhibit predictable degradation patterns: the Attention U-Curve (diminished recall for mid-context tokens), attention scarcity, context clash (Zombie context), and context poisoning.

This skill provides deterministic protocols for compressing context, preserving artifact integrity, actively pruning contradictory context, and maximizing the signal-to-noise ratio in long-horizon coding sessions.


When to Activate

Activate this skill when:

  • Sessions extend beyond 10+ turns or involve massive codebase exploration.
  • Agent begins "forgetting" files it previously modified or decisions made earlier.
  • Managing interactive multi-turn planning sessions (/plan).
  • Diagnosing attention failures, hallucinations, or context poisoning.
  • Designing compaction and handoff summaries for multi-phase tasks.
  • Integrating ephemeral scratchpad outputs with persistent semantic memory (MemPalace).

Do NOT activate for:

  • Simple, single-turn query answering or typo fixes.
  • Low-level database indexing (use skill-backend-architect).

1. The Attention U-Curve & Placement Strategy

Models attend strongly to the beginning (system instructions, initial prompt) and the end (recent turns, immediate directives) of their context window. Information placed in the middle experiences a 10% to 40% reduction in retrieval fidelity.

High Attention │ █                                         █
               │ ██                                       ██
               │ ███                                     ███
               │ ████                                   ████
Low Attention  │ ███████████████████████████████████████████
               └─────────────────────────────────────────────►
                 Beginning            Middle              End
               (Rules/Persona)   (References/Logs)     (Active Task)

Placement Protocol:

  1. Top (System Prompt / Static Rules): Core invariants, safety guardrails, tool schemas.
  2. Middle (Dynamic Overflow): Reference file contents, search findings, and scratchpad pointers.
  3. Bottom (Active Anchor): Active task goal, acceptance criteria, current step checklist, and explicit next command.

2. Anchored Iterative Summarization (Compression Schema)

When compressing long conversation histories, avoid freeform summaries that silently discard critical identifiers. Maintain an Anchored Structured Summary populated using this mandatory schema:

# Session State Summary

## 1. Active Intent & Scope
- Objective: [Clear 1-sentence goal]
- Acceptance Criteria: [Testable conditions of completion]

## 2. Artifact Trail (Strict File Tracking)
- Created Files:
  - `path/to/new_file.ts` (Exports: `UserService`, `AuthMiddleware`)
- Modified Files:
  - `path/to/existing.py` (Functions changed: `validate_token`, `refresh_session`)
- Inspected / Read-Only Files:
  - `path/to/config.yml` (Verified schema version 2.4)

## 3. Decisions & Invariant Contracts
- [DECISION] Using Redis connection pool (max 20 connections) instead of per-request clients.
- [INVALIDATED] Removed initial hypothesis about memory leak in worker thread; root cause was unclosed HTTP client.

## 4. Current State & Verification Baseline
- Tests: 42 passed, 0 failed.
- Build: Clean TypeScript compilation (`npx tsc --noEmit` passed).

## 5. Next Immediate Actions
1. Implement integration test for refresh endpoint.
2. Trigger 5-axis review before commit.

3. Context Garbage Collection & Active SSOT (Anti-Zombie Context)

A critical failure mode during planning and refactoring is Context Clash: leaving old, revoked implementations in the active text while trying to adopt new requirements.

The Anti-Zombie Context Protocol:

  1. Single Active Truth: The active working specification must contain ONLY current, valid code. If a framework or DB choice is revoked, remove its active code blocks entirely.
  2. 1-Line Atomic Tombstones: Keep historical awareness without attention pollution by recording a single line in the decision log: - [PRUNED Turn N]: Revoked PostgreSQL in favor of SQLite (User decision).
  3. Scratchpad Archiving: If an abandoned design is large (>50 lines), offload it to <appDataDir>/brain/<id>/scratch/archived_<feature>.md rather than keeping dead text in the active context.

4. Optimizing Tokens-Per-Task (Anti-Re-Fetching)

Measure efficiency by Tokens-Per-Task (total tokens needed to complete the overall objective), NOT tokens-per-turn.

  • Overly aggressive compression that strips full file paths or specific function names causes the model to re-read files repeatedly, multiplying token costs.
  • Preserve Specific Identifiers: Always preserve exact file paths, exported symbol names, error codes, and line numbers across compression cycles.

5. Context Poisoning Circuit Breaker

When an invalid assumption or tool hallucination enters context, it compounds through self-reference.

  1. Quarantine: Immediately label the invalid assumption with [INVALIDATED: Reason].
  2. Re-anchoring: Do NOT stack multiple conversational retries. Re-read the source of truth file (view_file) and restart the reasoning step from verified baseline data.

6. Persistent Memory Sync (MemPalace Protocol)

For knowledge that must survive across separate sessions and project restarts:

  1. Extract architectural decisions, learned conventions, and domain facts.
  2. File memories into MemPalace using mempalace_kg_add or mempalace_diary_write.
  3. Invalidate superseded facts with mempalace_kg_invalidate to prevent knowledge graph clash.

7. Anti-Rationalization Table

Agent ExcuseBLOCKED Rebuttal
"I'll just write a vague 2-line summary like 'we worked on auth'."BLOCKED: Omission of the Artifact Trail causes expensive re-exploration loops. Follow the 5-section schema.
"I left deprecated code in the prompt so the user remembers what we changed."BLOCKED: Violates Anti-Zombie Context. Deprecated code causes context clash. Use 1-line tombstones in Decision Log.
"The model has a massive context window so compaction is unnecessary."BLOCKED: Performance degrades smoothly along the Attention U-Curve. Compact context keeps reasoning sharp.

8. Verification Gates

  • Does the context summary include the full Artifact Trail (created, modified, read files)?
  • Are active acceptance criteria positioned at the bottom of the prompt/reasoning anchor?
  • Has deprecated/zombie code been excised from active working specs?
  • Have all discarded hypotheses been marked as [INVALIDATED] or [PRUNED]?
  • Are cross-session learnings synchronized to MemPalace?

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.