context-slim — shrink potential context sources
Caution
Discovery is not proof of loaded context. The scan inventories potential sources: startup instructions, recursive rules, imported conventions, client-dependent AGENTS.md, memory, agent definitions, and skill resources. Path-scoped rules load conditionally; only selected agent bodies and read skill references apply to a particular run. Use measure for inventory sizes, then inspect runtime context before claiming actual session cost.
Tip
Three levers, one coordinated pass. Cross-layer dedup, generic-knowledge removal, and per-file compression preserve protected values, paths, pins, and non-default instructions. A failed gate prevents acceptance. Recovery is limited to proven owned drafts; concurrent changes remain intact.
Quick reference
| Field | Value |
|---|---|
| Command | /brewtools:context-slim |
| Arguments | [prompt] [measure|preview|slim|hard|bodies|restore] [--target=N%] [--global] [--memory] [--noask] [ts] |
| Model | opus |
| Context | session |
| Tools | Read, Edit, Write, Bash, Grep, Glob, Agent, AskUserQuestion |
What it does
The skill coordinates potential context sources across three inventory tiers: startup/conditional instructions, per-spawn agent bodies, and per-invocation skill bodies/references. Tier membership describes when a source may load, not observed loading in your session.
Recursive rule/reference discovery follows linked directories while detecting cycles and unsafe or unreadable paths. An incomplete scan is reported as partial: stop measurement and optimization instead of publishing totals, savings, or new run state from an incomplete inventory.
A bare invocation measures and reports without target edits. Slim, hard, and bodies require a byte-exact snapshot before target edits and the source’s project-target cleanliness gate; the global layer has its own snapshot. Restore is a separate recovery operation and requires matching existing owned-draft proof before overwriting current bytes.
Every optimization run verifies protected tokens and uses independent semantic checks on dropped or merged facts. Any miss fails acceptance. Whole-run recovery across touched layers proceeds only when snapshots and recorded ownership prove it is safe; otherwise current bytes are preserved and recovery refusal is reported.
When to use
- CLAUDE.md keeps growing — measure the potential inventory before deciding what to compress
- Onboarding a new machine or repo — inventory potential sources and loading conditions before adding rules
- Rules duplicate across files — cross-layer dedup finds facts repeated between project and global layers
- Skill or agent bodies feel bloated —
bodiesmode extends scope toSKILL.mdandreferences/*.md, which are normally excluded - A prior slim pass wasn’t aggressive enough — an unmet
--targettriggers the same lossy-pass confirmation in any mutating mode;hardjust lets that pass cut further once approved - Something broke after a compression run — request checkpoint-proven recovery through restore
Modes
| Mode | What it does | Mutates? |
|---|---|---|
measure | Reports potential inventory size proxies per tier/file, not loaded-context tokens. Default with empty input | no |
preview | Runs discovery through the dedup analysis and prints the projected plan and token delta | no |
slim | Full lossless compression: dedup, default-knowledge removal, per-file rewrite, verify | yes |
hard | Same as slim; when a --target isn’t met losslessly, the escalation gate (which fires in any mutating mode) is allowed to cut further | yes, destructive |
bodies | Extends scope to SKILL.md and references/*.md (normally opt-in only). Combine with preview/slim/hard, or alone it means bodies + slim | yes |
restore | Requests prior-snapshot recovery using last, a timestamp, or —run-dir; refuses unsafe overwrites | yes, destructive |
Examples
# Bare invocation — measure only, no writes, no questions asked
/brewtools:context-slim
# Russian-language prompt — resolved to slim mode from keywords
/brewtools:context-slim сожми контекст, почисти дубли в правилах
# Target ratio, including the global layer (asks for confirmation on the global write)
/brewtools:context-slim slim --target=30% --global
# Request checkpoint-proven recovery of the most recent run
/brewtools:context-slim restore last
Flow
- Phase 0 — resolve mode and scope
Parses the free-form prompt for an explicit mode token or keyword score, applies flags (
—target,—global,—memory,—noask), and asks at most oneAskUserQuestion— only when the answer changes what gets written.measureand—noaskskip this entirely; destructive-mode and global-write confirmations always fire regardless. - Phase 1 — discover and measure
Run context-scan.sh over the resolved scope for per-file inventory sizes and loading conditions. Its bytes/4 proxy is not a tokenizer measurement. The report marks actual loading as unobserved; measure stops after reporting.
- Phase 2 — snapshot (fail-closed)
Copies every target byte-exact into a timestamped run directory under
~/.claude/backups/, one directory per layer. The project layer requires a clean git tree first — a dirty tracked target refuses the run and names the exact paths to commit or stash. - Phase 3 — cross-layer dedup analysis
Orchestrator-only barrier: a mechanical prefilter over exact and near-duplicate content, followed by an LLM judgment pass on candidate pairs. Produces a per-file drop/keep decision list.
previewstops here and prints the projected delta. - Phase 4 — per-file compression
Spawn one text-optimizer per file with its ownership and assigned dedup decisions. Originals remain immutable but readable. Immediately after each known owned edit/deletion/repair, record the draft checkpoint before further edits/checks. Exclude this skill’s own directory from fan-out.
- Phase 5 — verify (barrier)
Verify with —no-restore, then use independent read-only comparison against original evidence. A miss fails acceptance. Repair owned loss or attempt safe checkpoint-proven recovery; missing proof or changed current bytes refuses restoration.
- Phase 6 — re-measure and escalation gate
Re-scans the same scope and compares against phase 1. A met or absent
—targetmoves straight to phase 7. An unmet target on a virgin surface reports the shortfall without asking; on a surface with prior ratchet state, it asks once whether to approve a lossy pass. - Phase 7 — ratchet state and report
Write state with before/after inventory proxies, achieved ratio, and the drop ledger. Report measurement method, loading limits, verification/recovery results, contradictions, untouched-surface advice, and escalation outcome.
Safety and rollback
Every mutating run is snapshotted before a single byte is written. The project layer’s snapshot is gated on a clean git tree over the target files — untracked or git-ignored files are still snapshotted (SNAPSHOT-ONLY, never refused) since git has no pre-state to fall back on for those. The global layer, when in scope, gets its own snapshot under ~/.claude/backups/<ts>-global_context-slim/, separate from the project run directory, so a same-second collision across layers can’t happen.
Original snapshots are comparison evidence. Recovery must validate the prior manifest and recorded owned drafts across all touched layers. Missing state, damaged originals, or current bytes changed by another writer prevents restoration; never create a checkpoint at failure time to bypass it.
To request recovery of a prior run:
/brewtools:context-slim restore last
What it never touches
| Surface | Handling |
|---|---|
| MCP servers | Signal only — reported as advice in the final report, never mutated |
| Plugin enablement | Signal only — reported as advice, never mutated |
settings.json | Signal only — reported as advice, never mutated |
~/.claude/plugins/cache/** | Read for signals, never written |
The scanner’s legacy token_model label chars/4 represents a bytes/4 inventory proxy. Unicode and tokenizer differences are corpus-dependent. Do not describe proxy reductions as measured token savings or treat recursively discovered files as all loaded at startup.
ToolSearch can defer tool schemas where the client supports discovery. MCP server count alone does not establish context cost, and a mention of lazy loading is not proof that a schema was absent from a particular session. MCP advice remains advisory; this skill never rewrites settings.
Text Optimize
The per-file compression subagent context-slim fans out to in phase 4.
GitHub source
Source code, scripts, and the full decision-rule reference set.
Brewtools overview
All brewtools skills — text, secrets, SSH, deploy, plugin management.
Updating plugins
/brewtools:plugin-update to check and update the brewcode plugin suite in one command.
See the FAQ for details.