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

FieldValue
Command/brewtools:context-slim
Arguments[prompt] [measure|preview|slim|hard|bodies|restore] [--target=N%] [--global] [--memory] [--noask] [ts]
Modelopus
Contextsession
ToolsRead, 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 — bodies mode extends scope to SKILL.md and references/*.md, which are normally excluded
  • A prior slim pass wasn’t aggressive enough — an unmet --target triggers the same lossy-pass confirmation in any mutating mode; hard just lets that pass cut further once approved
  • Something broke after a compression run — request checkpoint-proven recovery through restore

Modes

ModeWhat it doesMutates?
measureReports potential inventory size proxies per tier/file, not loaded-context tokens. Default with empty inputno
previewRuns discovery through the dedup analysis and prints the projected plan and token deltano
slimFull lossless compression: dedup, default-knowledge removal, per-file rewrite, verifyyes
hardSame as slim; when a --target isn’t met losslessly, the escalation gate (which fires in any mutating mode) is allowed to cut furtheryes, destructive
bodiesExtends scope to SKILL.md and references/*.md (normally opt-in only). Combine with preview/slim/hard, or alone it means bodies + slimyes
restoreRequests prior-snapshot recovery using last, a timestamp, or —run-dir; refuses unsafe overwritesyes, 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

  1. 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 one AskUserQuestion — only when the answer changes what gets written. measure and —noask skip this entirely; destructive-mode and global-write confirmations always fire regardless.

  2. 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.

  3. 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.

  4. 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. preview stops here and prints the projected delta.

  5. 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.

  6. 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.

  7. Phase 6 — re-measure and escalation gate

    Re-scans the same scope and compares against phase 1. A met or absent —target moves 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.

  8. 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

SurfaceHandling
MCP serversSignal only — reported as advice in the final report, never mutated
Plugin enablementSignal only — reported as advice, never mutated
settings.jsonSignal 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

Use /brewtools:plugin-update to check and update the brewcode plugin suite in one command. See the FAQ for details.