context-hygiene
Use when context is growing large or the agent forgets earlier instructions, when deciding clear vs compact, when processing documents/logs >50k tokens, when…
Skill by Leostruka
Install
Works with Claude Code, Claude apps, Codex, Cursor, Gemini CLI, GitHub Copilot, VS Code, OpenCode, Goose, Windsurf. Read the repository before you give any tool access to your data.
npx agentmarket install skill/leostruka-context-hygiene
Asks which of your tools to add it to (Claude Code, Codex, Cursor, VS Code, Windsurf, Gemini CLI, Claude Desktop) and shows the change first. See https://agentmart.dev/cli.
Get the weekly diff
The weekly diff: one email a week with new agent tools, notable updates and grade changes, plus security alerts for tools you follow. Double opt-in, one-click unsubscribe.
About
Use cases: agent-building
Reviews
Write a reviewNo reviews yet. Installed it? Reviews come from verified installers only. How reviews work
Permissions
What this skill can do and what it asks for, from its SKILL.md. Checked Oct 25, 2026.
- Tools
- No tools found
- Secrets
- None asked for
- Install scripts
- None found
Network hosts it talks to 1
codeload.github.com· found in install command
Files it touches
~/.claude/skills/context-hygiene
What's inside
- Skill name
context-hygiene- Description
- Use when context is growing large or the agent forgets earlier instructions, when deciding clear vs compact, when processing documents/logs >50k tokens, when monitoring token cost or limiting subagent fan-out, when choosing a reasoning effort level, or when reducing token/compute/MCP costs. Covers lost-in-the-middle, context folding (RLM), cost guards, and difficulty-matched effort.
- License
- MIT
- Instructions
- 142 lines in SKILL.md · view on GitHub
Files (1)
- SKILL.md
SKILL.md (first lines)
# Context Hygiene
Context window = input + output tokens the model sees at once. Every system
prompt, rules file, MCP tool definition, message, and tool result counts
against a hard provider-set limit. Output quality degrades past ~100k active
tokens ("dumb zone") regardless of total window — lost-in-the-middle means
middle detail has weak impact (arXiv:2307.03172). Bigger window ≠ better
retrieval.
**Default stance:** with SWE-2 (262K) most sessions fit — use context
directly. Apply the techniques below only when actually needed.
## Clear vs Compact
| Action | What it does | When |
|---|---|---|
| `clear` | Wipes history | **Default.** Task done or unrelated to prior chat. |
| `compact` | Summarizes history | Same task continues; losing thread would hurt. Lossy — preserves intent, not facts. |
Compaction leaves "sediment" — treat it as escape hatch, not hygiene default.
If dense access to early detail is needed, fold (below) instead.
## Prune vs Fold vs Compact vs Summarize
| Action | Mechanism | When |
|---|---|---|
| Prune | Per-item keep/truncate/drop via `extensions/laya-compactor` (laya `compact-item-v1`, suggestion/abstain only) | Tool noise fills the window; facts must survive verbatim. |
| Fold | Offload artifacts to files; peek/grep/sub-query | Dense access to early detail needed; >50k-token artifacts. |
| Compact | `compact` summary | Escape hatch when pruning cannot reach target size. |
| Summarize | Manual tl;dr | Almost never inside a session; for handoffs write a doc instead. |
Pruning decision policy lives here: pin system + first message + last user
task + newest `preserve_recent` messages; abstain means keep (fail-safe);
drop applies pair-wise so no `tool_result` is orphaned; survivors stay
byte-identical. Escalate to `compact` summary only when pruning cannot
reach `compact_to`.
**Smart Window params** (adaptive effective window, not fixed recency):
| Param | Value | Basis |
|---|---|---|
| `compact_at` | 0.70 x window (SWE-2 262k -> ~183k) | headroom for next tool batch |
| `compact_to` | 0.40 x window (~105k) | hysteresis, avoids thrash |
| `preserve_recent` | 6 messages + first message | upstream port default |
| `keep_threshold` | 0.5, calibrate on real transcripts | laya confidence is entropy-based |
| `truncate_head` | 300 chars | upstream port default |
| `max_state` | ~25k est. tokens | fits laya context |
| `reduction_floor` | <0.25 -> abort, keep original | avoids pointless churn |
`assist` mode requires `activation_errors` empty plus a calibrated
threshold; run shadow first, measure, then promote.
## Lean Context Rules
1. Clear chats between unrelated tasks.
2. Keep rules files small — they load into *every* conversation. Modularize
into skills; see `writing-skills`.
3. Be paranoid about MCP servers — each injects every tool definition into
the system prompt. Audit with `mcp-governance` before adding; keep <10-15
tools/server.
4. Don't paste huge documents — write to file, then `read` offset/limit or
`grep`.
5. Prefer subagents for parallel exploration — each has its own window; only
synthesis returns (50-100x savings).
6. Watch the budget — `context-budget.py` (SessionStart hook).
7. Guard against overflow — unbounded loops are a cost and correctness risk.
## Context Folding (RLM-style, for >50k-token artifacts)
Adapted from Recursive Language Models (arXiv:2512.24601): treat context as a
variable in an environment — peek, grep, partition, sub-query — instead of
reading it all.
Workflow: **offload** to file → **peek** (read offset/limit) → **grep** to
locate → **partition** (`split -l 500`) → **sub-query** chunks with
`researcher` subagents → **verify returns** (Rule 12 spot-checks) →
**synthesize**.
**Depth rule (critical):** depth=1 only. Subagents must NOT spawn subagents —
depth=2 causes overthinking, 95x slower (arXiv:2603.02615).
Don't fold preemptively, don't dump whole files into context, don't use for
simple retrieval (grep is cheaper).
**Reversible folds** (`scripts/fold_store.py`, inspired by billion-context):
when you fold a range the session may need again, persist it with an id —
the summary stays in context, the content survives on disk.
```bash
python skills/context-hygiene/scripts/fold_store.py save <id> \
--summary "one line" --content-file huge_log.txt # fold away
fold_store.py unfold <id> # restore full text when needed
fold_store.py grep <keyword> # find which fold holds a detail
fold_store.py list # ids, summaries, est. tokens
```
Fold ids are durable across sessions (`.devin/scratch/folds/`); delete
stale folds at task end to keep the store small.
## Cost Guard
| Limit | Action |
|---|---|
| 1-3 subagents | Default max; >3 requires explicit user approval (enforced by `validate-tool-args.py`). |
| Loops/retries | Bound every loop; each iteration multiplies cost. |
| Token maxing | Detect effort disproportionate to task difficulty. |
## Cost Optimization Protocol
1. Measure current cost (tokens/request, model tier, cache hit rate).
2. Audit context usage (`mcp-governance` for MCP tool-definition cost).
3. Right-size effort (see below); paid models only when explicitly approved.
4. Add caching; shorten prompts; prefer file snippets over full reads.
5. Re-measure; report tokens/cost before and after with commands used.
## Code-formatting minification — scoped caution
Stripping non-semantic whitespace cuts **input** tokens ~24.5% (arXiv:2508.13666,
ICSE'26 — Java 33.7% avg; tool: Deblank). Verified but **narrow**: measured onFrom Leostruka/devin-bundle, MIT.
More from Leostruka/devin-bundle
- 0.570score
debugging
Leostruka
Use when the user says 'diagnose', 'debug this', reports something broken/throwing/failing/slow, when encountering a bug/test failure/unexpected behavior and…
SkillAFreshness: AClaude Code +9 - 0.565score
ask-bundle
Leostruka
Use when deciding which skill or flow fits your situation — the meta-router entry point for this bundle (direct specialist skills, multi-skill flows, local…
SkillAFreshness: AClaude Code +9 - 0.565score
code-review
Leostruka
Use when completing a task, reviewing a branch or PR, before merging, when the user asks to 'review since X', when publishing a GitHub PR review with inline…
SkillAFreshness: AClaude Code +9 - 0.565score
ai-tools
Leostruka
Use when running local, offline-first ML tooling — mechanistic interpretability PoCs like refusal-direction ablation on local safetensors or the HF cache, or…
SkillAFreshness: AClaude Code +9 - 0.565score
animation-direction
Leostruka
Use when turning narrated video/audio into synced code-rendered motion graphics — narration -> timestamped transcript -> scene plan -> approval gate ->…
SkillAFreshness: AClaude Code +9 - 0.565score
architecture
Leostruka
Use when designing modules, seams, and adapters, when evaluating module depth and identifying deepening opportunities in a codebase, or when modernizing…
SkillAFreshness: AClaude Code +9 - 0.565score
architecture-diagrams
Leostruka
Use when the deliverable is a physical diagram artifact (.svg/.png) — C4 models, dense class diagrams, network topology rendered via PlantUML.
SkillAFreshness: AClaude Code +9 - 0.565score
computer-use
Leostruka
Use when you need to see or control the local screen (screenshots, screen recording with video + contact sheet for catching transient bugs/animations, mouse…
SkillAFreshness: AClaude Code +9 - 0.565score
cu-realtime
Leostruka
Use when computer-use or terminal automation needs the fastest reaction the runtime allows - event waits instead of screenshot polling, text perception…
SkillAFreshness: AClaude Code +9 - 0.560score
ascii-art
Leostruka
Use when generating animated ASCII art for artifacts the agent produces - README banners (SVG), CLI splash screens, loading/404 states or decorative pieces in…
SkillAFreshness: AClaude Code +9 - 0.539score
data-analyst
Leostruka
Use when the user asks to query a database, analyze data, create charts/visualizations, explore data patterns, or asks business questions about data.
SkillAFreshness: AClaude Code +9 - 0.539score
database
Leostruka
Use when the user wants to design, migrate, query, or optimize a database.
SkillAFreshness: AClaude Code +9
Signals
- Stars
- 0
- Forks
- 0
- Open issues
- 1
- Last commit (this folder)
- Oct 10, 2026 (18 days ago)
- Last release
- Oct 24, 2026 (4 days ago)
From GitHub (fetched Oct 24, 2026).
Details
- License
- MIT
- Repository
- github.com/Leostruka/devin-bundle
- First seen
- Oct 24, 2026
- Last checked
- Oct 24, 2026
- Source
- GitHubgithub-graphql
More from Leostruka
- 0.570score
debugging
Leostruka
Use when the user says 'diagnose', 'debug this', reports something broken/throwing/failing/slow, when encountering a bug/test failure/unexpected behavior and…
SkillAFreshness: AClaude Code +9 - 0.565score
code-review
Leostruka
Use when completing a task, reviewing a branch or PR, before merging, when the user asks to 'review since X', when publishing a GitHub PR review with inline…
SkillAFreshness: AClaude Code +9 - 0.565score
ask-bundle
Leostruka
Use when deciding which skill or flow fits your situation — the meta-router entry point for this bundle (direct specialist skills, multi-skill flows, local…
SkillAFreshness: AClaude Code +9 - 0.565score
ai-tools
Leostruka
Use when running local, offline-first ML tooling — mechanistic interpretability PoCs like refusal-direction ablation on local safetensors or the HF cache, or…
SkillAFreshness: AClaude Code +9 - 0.565score
animation-direction
Leostruka
Use when turning narrated video/audio into synced code-rendered motion graphics — narration -> timestamped transcript -> scene plan -> approval gate ->…
SkillAFreshness: AClaude Code +9 - 0.565score
architecture
Leostruka
Use when designing modules, seams, and adapters, when evaluating module depth and identifying deepening opportunities in a codebase, or when modernizing…
SkillAFreshness: AClaude Code +9
Cite this page
context-hygiene skill. Agent Mart. https://agentmart.dev/skills/leostruka-context-hygiene (last updated 2026-10-24)