# ctxslim Safe, deterministic, **reversible** context compression for Claude Code tool outputs. When a Bash command or MCP tool returns a large result, a PostToolUse hook replaces it in-context with a digest that fits the content: JSON records become a table with a profile of every row, diffs keep their full file list, search results and diagnostics are grouped by file, source files get an outline with line numbers, logs keep their errors and pattern counts, and a rerun of the same command becomes a diff. The first line of every digest says how to get the full original back from a local store. Inspired by [Headroom](https://github.com/chopratejas/headroom), minus everything heavy or risky: no ML models, no network access ever, no proxy in your request path. Python stdlib only — zero dependencies. ## What it guarantees - **Reversible** — the original is saved to `~/.ctxslim/store/` *before* any rewrite; `slim get ` returns it byte-identical (including `\r\n` and control bytes). - **Fail-open** — any error in the hook → exit 0 with no output → Claude Code uses the untouched original. A bug in one digest strategy degrades to a plain head/tail cut. - **Bounded** — one budget (default: the pass-through threshold, 4,000 chars of prose-equivalent text) caps every digest. Output under the threshold, or that cannot be reduced by at least 20%, passes through byte-identical. - **Lossless first** — when a re-encoding of the *whole* output fits the budget (a table instead of pretty-printed JSON, paths grouped by directory, matches grouped by file) nothing is omitted, and the header says so. - **Honest about omissions** — every omission marker carries the line range it replaces; error/warning lines that could not be shown are counted, never dropped silently; rare values and error rows hidden in the middle of a list are surfaced. - **Deterministic** — content-hash ids, no timestamps or randomness in digests: the same output always yields the same bytes, which keeps Anthropic prompt-cache prefixes reusable. No network access is involved. - **References only to what is still in context** — a repeat reference or rerun diff is only emitted to the same agent in the same session, after the last compaction or `/clear`, and never for a truncated output window. ## Install Requires Python ≥ 3.10. No dependencies. ```bash git clone https://github.com/AviadP/ctxslim.git ~/ctxslim uv tool install --editable ~/ctxslim # puts `slim` on PATH; `git pull` updates it ``` or, with a plain virtualenv: ```bash cd ~/ctxslim && python3 -m venv .venv && .venv/bin/pip install -e . ``` Neither needs "activating": the hook calls the executable by absolute path. ## Enable the hooks ```bash slim hooks # prints the settings.json snippet with the right absolute path ``` Merge it into `~/.claude/settings.json` (or a project's `.claude/settings.json`) and restart Claude Code — hooks load at session start: ```json { "hooks": { "PostToolUse": [ { "matcher": "Bash", "hooks": [{ "type": "command", "command": "/ABS/PATH/slim hook", "timeout": 10 }] }, { "matcher": "mcp__.*", "hooks": [{ "type": "command", "command": "/ABS/PATH/slim hook", "timeout": 10 }] } ], "SessionStart": [{ "hooks": [{ "type": "command", "command": "/ABS/PATH/slim hook", "timeout": 10 }] }], "PostCompact": [{ "hooks": [{ "type": "command", "command": "/ABS/PATH/slim hook", "timeout": 10 }] }] } } ``` `SessionStart` and `PostCompact` are optional. They tell ctxslim when the conversation's context was reset, so "identical to an earlier result" can never point at something that was compacted away. Without them, only output from the last 30 minutes is referenced (`CTXSLIM_REF_WINDOW`). If an MCP tool returns text you need verbatim (a file reader whose output you then edit), narrow the matcher to exclude it. `Read`, `Edit`, `Write` and the notebook tools are never rewritten even if matched. ### Check it works ```bash slim doctor # store, end-to-end hook self-test, PATH, hook registration ``` Then, in a fresh Claude Code session, ask it to run `seq 1 900 | sed 's/^/record line number /'` and quote the first line of the tool output: it should start with `[ctxslim`. Afterwards `slim stats` shows what was saved. ## How it fits with Claude Code's own limits - Bash output is read back up to ~30,000 chars; larger results reach the model as a saved-file path plus a 2,000-char preview. ctxslim therefore works on the 4k–30k range, where the alternative is the full text in context. For a truncated window (output cut at exactly the limit) it produces a short digest that says so, and never calls two such windows identical. - MCP text results are inlined up to ~50,000 chars — the largest savings. - **Failed commands are never rewritten.** A non-zero exit is delivered by Claude Code as a tool failure (`PostToolUseFailure`), which hooks cannot modify, so a failing test run always arrives exactly as the harness produced it. ## CLI ```bash | slim # pipe mode: digest + store slim get # full original, byte-identical slim grep # search the original slim lines 100-200 # 1-based inclusive range (same numbering digests print) slim ls # stored originals slim stats # chars kept out of context, by digest type slim clean # purge expired entries (also happens automatically) slim hooks | slim doctor # setup helpers ``` A digest header: ``` [ctxslim digest 28,712→2,744 chars · full: slim get 9f1c22ab · slim grep 9f1c22ab · slim lines 9f1c22ab A-B] ``` If `slim` is not on PATH, headers use the absolute invocation instead, so the command the model is given always exists. ## Configuration (env vars) | Variable | Default | Meaning | |---|---|---| | `CTXSLIM_THRESHOLD` | `4000` | chars below which output passes through untouched | | `CTXSLIM_BUDGET` | = threshold | upper bound for a digest, in prose-equivalent chars; token-dense content (hex, paths, numbers) gets proportionally fewer | | `CTXSLIM_TTL` | `86400` | seconds before stored originals are purged | | `CTXSLIM_STORE` | `~/.ctxslim/store` | where originals and session logs are kept | | `CTXSLIM_REF_WINDOW` | `1800` | without lifecycle hooks: how far back repeats are referenced | ## What each kind of output becomes | Input | Digest | |---|---| | Same bytes this agent was already shown | one-line reference naming the earlier command | | Rerun of the same command, mostly unchanged | unified diff vs the previous output; at most 3 diffs in a row, then a full digest again | | JSON (also JSON cut off by an output limit) | compact; arrays of records → table, nested records flattened to dotted columns; **profile of all rows** (value counts, ranges, constants) and **notable rows** (rare values, error-ish strings); sha256-size digests and base64 blobs clipped, shorter ids (ObjectIds, git SHAs) kept whole | | JSON lines | the same table, numbered by source line | | Unified diff (`git diff/show/log -p`) | commit message, **every file** with ±counts and its line range, then changed lines of whole hunks, round-robin across files | | `path:line: text` (grep, rg, linters, compilers) | grouped by file — path once; every file listed with its count; per-code summary with one example each, so a rare error among hundreds survives | | Path listings (`find`, `git ls-files`) | grouped by directory, extension counts | | CSV/TSV | header, first/last rows, notable rows, column profile | | Source code, markdown, config (by content or `cat file.ext`) | head + tail + **outline** of the omitted part with line numbers | | Logs / repetitive output | head, tail, every error with its traceback frames, one-off lines, and the top repeating patterns with counts | | Anything else | head/tail window plus error lines, with hidden error lines counted | | Colour codes and `\r` progress redraws | removed first — often that alone is enough. Records that merely *end* in `\r` are kept, never overwritten | | Minified / encoded blobs | short prefix and suffix | ## What is stored locally Originals of outputs of 1,500+ chars (so a later rerun can be diffed) and a per-session log of what was shown, under `CTXSLIM_STORE`, mode 0700/0600, purged after `CTXSLIM_TTL`. Nothing leaves the machine. Tool output can contain secrets: the store is as sensitive as your shell history. ## Measured `bench/` is a deterministic, stdlib-only benchmark: 23 tool outputs in the size range Claude Code actually inlines (API JSON, kubectl, npm, pytest, access/app logs, file listings, source code, diffs, grep/lint/compiler output, markdown, JSON lines, ANSI-coloured progress, CSV…) plus 3 rerun scenarios, run through the real hook with the harness limits modelled. Two numbers per sample: - **tokens** injected into context, by a local BPE-approximating estimator; - **retention**: the share of *probe facts* — error messages, file names, headings, record ids, summary lines, the one unhealthy item — that survive in what the model sees (`bench/probes.py`). A proxy for "can it still answer", applied identically to every version. ```bash python3 bench/run.py --compare bench/baseline_v0.2.json --compare bench/baseline_v0.1.json ``` | | tokens | retention | |---|---|---| | no hook | 281,622 | 100% | | v0.1 | 72,243 | 65% | | v0.2 | 40,278 | 62% | | **v0.3** | **25,471** | **94%** | v0.3 injects 91% fewer tokens than no hook, 37% fewer than v0.2 and 65% fewer than v0.1, while retaining far more. The retention metric did not exist before v0.3; it showed that v0.2's savings had come partly at the expense of fidelity on content the earlier benchmark did not cover (source code, diffs, search results, compiler errors). Lowering `CTXSLIM_BUDGET` trades retention for tokens smoothly — 3000: 22.0k tokens at 91%; 2500: 19.3k at 87% — still above both earlier versions on both axes. The default favours fidelity. Limits of the measurement: token counts are estimates (relative comparisons are reliable, absolute counts drift by a few percent); the corpus is synthetic; retention checks that facts are *present*, not that a model uses them. ## Non-goals No ML/semantic compression, no LLM calls, no proxy mode, no secret redaction, no conversation-history compaction (Claude Code already does that). ## Tests ```bash python3 -m pytest ```