{"id":"ca6e01e7-bbc4-4271-9362-8a619218a969","slug":"cozempic","kind":"skill","name":"cozempic","summary":"Context cleaning for Claude Code — prune bloated sessions, protect Agent Teams from context loss, auto-guard with tiered pruning","owner":"Ruya-AI","repoUrl":"https://github.com/Ruya-AI/cozempic","license":"MIT","licenseTier":"permissive","trust":"community","stars":425,"match":null,"fewStars":false,"format":"skill","createdAt":null,"addedAt":"2026-10-14T05:53:17.124Z","logoUrl":"https://avatars.githubusercontent.com/u/189677034?v=4","linkOnly":false,"collection":null,"skillPath":null,"categories":["memory-knowledge","developer-tools","communication"],"tags":["claude-code","context","llm-tools","agent-teams","cli","context-management","jsonl","pruning"],"runtime":"python","local":true,"cloudCapable":false,"cloudCapability":"unknown","cloudReadyOnPlatform":false,"needsApiKey":false,"reviewed":false,"syncedAt":"2026-10-14T06:00:31.482Z","sample":false,"url":"https://conduits.dev/tools/cozempic","language":"Python","transports":["stdio"],"install":{"pypi":"cozempic"},"requirements":{"env":[],"upstreamMayCharge":false},"tools":null,"readme":"# Cozempic\n\n![Downloads](https://img.shields.io/badge/downloads-100k%2B-brightgreen) ![Version](https://img.shields.io/badge/version-1.8.39-blue) ![License](https://img.shields.io/badge/license-MIT-lightgrey)\n\n**100,000+ power users** trust Cozempic to keep their Claude Code sessions lean.\n\nContext cleaning for [Claude Code](https://claude.ai/code) — **remove the bloat, keep everything that matters, protect Agent Teams from context loss**.\n\n## What It Does\n\nClaude Code sessions fill up with dead weight: progress ticks, thinking blocks, stale file reads, duplicate CLAUDE.md injections, base64 screenshots, oversized tool outputs, and metadata bloat. A typical session carries 8-46MB — most of it noise that inflates every API call.\n\nCozempic removes it with **18 composable strategies** across 3 prescription tiers, while your actual conversation, decisions, and working context stay untouched. The guard daemon runs automatically — install once, forget about it.\n\n### Key Features\n\n- **18 pruning strategies** — gentle (5), standard (11), aggressive (18)\n- **Guard daemon** — auto-starts via SessionStart hook, monitors and prunes continuously\n- **Interactive \"prune now?\" nudge** — a non-blocking heads-up at 25% / 55% / 80% context (once per tier) recommending `cozempic reload`, so interactive users get cozempic's higher-fidelity prune+resume on their own terms instead of falling back to lossy autocompact. Takes no action on its own; silence with `COZEMPIC_NUDGE_OFF=1`\n- **Interactive-safe reload** — in interactive sessions the guard warns first and reloads only at an idle breakpoint (never mid-turn); headless sessions reload as before\n- **Safe-point protection** — the guard never terminates-and-resumes through in-flight work: a running Workflow, a background subagent, an agent team, or an open tool call defers the reload so nothing is lost\n- **compact-summary-collapse** — 85-95% savings by removing pre-compaction messages already in the summary\n- **Agent Teams protection** — checkpoints team state through compaction, reactive overflow recovery\n- **Behavioral digest** — extracts your corrections (\"don't do X\"), persists them to Claude Code's memory system so they survive compaction\n- **15 doctor checks** — diagnose and auto-fix session corruption, orphaned tool results, zombie teams, unresumable sessions\n- **Token-aware diagnostics** — exact token counts from `usage` fields, cache hit rate, context % bar\n- **Auto-detects 1M context** — correct thresholds for both 200K and 1M models\n- **Efficient idle polling** — backs off the poll cadence when the session is quiet and skips redundant no-op checkpoints\n- **Auto-updates** — checks PyPI daily, upgrades in-place\n\n**Zero external dependencies.** Python 3.10+ stdlib only.\n\n## Install\n\nPick your package manager. `uvx`/`pipx`/`npm`/`pip` are the lowest-friction (no Homebrew trust prompt — see the note below):\n\n```bash\n# uv — persistent install, always on PATH (recommended)\nuv tool install cozempic\n\n# uvx — run once without installing (handy to try it, but the guard daemon\n# can't auto-start from an ephemeral env — use `uv tool install` for that)\nuvx cozempic --help\n\n# pipx — isolated user install, always on PATH\npipx install cozempic\n\n# npm — global install\nnpm install -g cozempic\n\n# pip (Python ≥ 3.10)\npip install cozempic\n\n# Homebrew (macOS / Linux) — use the fully-qualified name (see note below)\nbrew install Ruya-AI/cozempic/cozempic\n\n# Nix flake\nnix profile install github:Ruya-AI/cozempic?dir=packaging/nix\n```\n\n> **Homebrew tap trust:** recent Homebrew versions gate non-official taps behind an explicit trust step. The **fully-qualified** `brew install Ruya-AI/cozempic/cozempic` above trusts just this formula inline — no extra command. A bare `brew install cozempic` / `brew upgrade cozempic` will instead error with *\"Refusing to load formula … from untrusted tap\"*; if you hit that, run `brew trust Ruya-AI/cozempic` once (or just prefer one of the install methods above, none of which have this gate).\n\nAUR (`yay -S cozempic`) and MacPorts (`port install py-cozempic`) submissions are in progress — see [`packaging/README.md`](packaging/README.md) for status and PKGBUILD/Portfile sources.\n\nThat's it. Cozempic auto-initializes on first use — hooks are wired globally, guard daemon auto-starts on every Claude Code session. No manual setup needed. Opt out with `COZEMPIC_NO_GLOBAL_INIT=1`.\n\n### Auto-update & how to control it\n\nCozempic auto-updates from PyPI by default, **on purpose**: Claude Code ships frequent changes to its session/context format, and auto-update is how a compatibility fix reaches you *before* a stale release can mishandle and lose your context. For most users that safety outweighs the convenience cost, so we recommend leaving it on. If you'd rather control it, set one of these — ideally in your shell profile (`~/.zshrc` / `~/.bashrc`) so it applies *before* the first session wires anything:\n\n| Goal | Set |\n|---|---|\n| Hold a specific reviewed version, keep hooks + guard running | `export COZEMPIC_PIN=1.8.30` |\n| Stop all auto-updates, keep hooks + guard running | `export COZEMPIC_NO_AUTO_UPDATE=1` |\n| No global hooks / no daemon at all (manual CLI only) | `export COZEMPIC_NO_GLOBAL_INIT=1` |\n\nBoth `COZEMPIC_NO_AUTO_UPDATE` and `COZEMPIC_PIN` are honored by the Python updater, the SessionStart hook's shell upgrade, and the npm installer. `COZEMPIC_PIN` disables auto-update and warns (not auto-installs) if your running version drifts from the pin, so you stay on a version you've reviewed with a human in the loop. (Releases are published from CI via PyPI [Trusted Publishing](https://docs.pypi.org/trusted-publishers/) — no long-lived upload token — to reduce the chance of a compromised publish in the first place.)\n\n### As a Claude Code Plugin\n\nInstall cozempic (any method above), then inside Claude Code:\n\n```\n/plugin marketplace add Ruya-AI/cozempic\n/plugin install cozempic\n```\n\nThis gives you MCP tools, skills (`/cozempic:diagnose`, `/cozempic:treat`, etc.), and auto-wired hooks.\n\n## Quick Start\n\n```bash\n# Auto-detect and diagnose the current session\ncozempic current --diagnose\n\n# Dry-run the standard prescription\ncozempic treat current\n\n# Apply with backup\ncozempic treat current --execute\n\n# Go aggressive on a specific session\ncozempic treat <session_id> -rx aggressive --execute\n\n# Check for session corruption\ncozempic doctor\n\n# View behavioral digest rules\ncozempic digest show\n\n# Show all strategies & prescriptions\ncozempic formulary\n```\n\n## Strategies\n\n| # | Strategy | Tier | What It Does | Expected |\n|---|----------|------|-------------|----------|\n| 1 | `compact-summary-collapse` | gentle | Remove all pre-compaction messages (already in the summary) | 85-95% |\n| 2 | `attribution-snapshot-strip` | gentle | Strip attribution-snapshot metadata entries | 0-2% |\n| 3 | `progress-collapse` | gentle | Collapse consecutive and isolated progress tick messages | 40-48% |\n| 4 | `file-history-dedup` | gentle | Deduplicate file-history-snapshot messages | 3-6% |\n| 5 | `metadata-strip` | gentle | Strip token usage stats, stop_reason, costs | 1-3% |\n| 6 | `thinking-blocks` | standard | Remove/truncate thinking content + signatures | 2-5% |\n| 7 | `tool-output-trim` | standard | Trim large tool results (>8KB or >100 lines), microcompact-aware | 1-8% |\n| 8 | `tool-result-age` | standard | Compact old tool results by age — minify mid-age, stub old | 10-40% |\n| 9 | `stale-reads` | standard | Remove file reads superseded by later edits | 0.5-2% |\n| 10 | `system-reminder-dedup` | standard | Deduplicate repeated system-reminder tags | 0.1-3% |\n| 11 | `tool-use-result-strip` | standard | Strip toolUseResult envelope field (Edit diffs, never sent to API) | 5-50% |\n| 12 | `image-strip` | aggressive | Strip old base64 image blocks, keep most recent 20% | 1-40% |\n| 13 | `http-spam` | aggressive | Collapse consecutive HTTP request runs | 0-2% |\n| 14 | `error-retry-collapse` | aggressive | Collapse repeated error-retry sequences | 0-5% |\n| 15 | `background-poll-collapse` | aggressive | Collapse repeated polling messages | 0-1% |\n| 16 | `document-dedup` | aggressive | Deduplicate large document blocks (CLAUDE.md injection) | 0-44% |\n| 17 | `mega-block-trim` | aggressive | Trim any content block over 32KB | safety net |\n| 18 | `envelope-strip` | aggressive | Strip constant envelope fields (cwd, version, slug) | 2-4% |\n\n### Prescriptions\n\n| Prescription | Strategies | Risk | Typical Savings |\n|---|---|---|---|\n| `gentle` | 5 | Minimal | 85-95% (with compact boundary) |\n| `standard` | 11 | Low | 25-45% |\n| `aggressive` | 18 | Moderate | 35-60% |\n\n**Dry-run is the default.** Nothing is modified until you pass `--execute`. Backups are always created.\n\n## Guard — Continuous Protection\n\nThe guard daemon monitors your session and prunes automatically:\n\n```bash\n# Auto-starts via SessionStart hook after cozempic init\n# Or run manually:\ncozempic guard --daemon\n```\n\n**4-tier proactive pruning** (every 30s):\n\n| Tier | Threshold | Action | Reload? |\n|------|-----------|--------|---------|\n| Soft | 25% | gentle file cleanup | No |\n| Hard | 55% | standard prune | Yes (interactive: at a breakpoint; deferred if agents active) |\n| Hard2 | 80% | aggressive prune | Yes (gated by the safe-point check) |\n| User | 90% | manual aggressive | Yes |\n\n**Interactive sessions** — instead of a surprise reload mid-work, the guard surfaces a [nudge](#key-features) and reloads only once you pause between turns, after warning you. Near the wall (≈88%) it reloads even mid-turn — a higher-fidelity prune beats hitting autocompact. Detection is automatic (`COZEMPIC_INTERACTIVE=auto`); `on`/`off` force it. Headless/CI sessions reload immediately as before.\n\n**Safe-point reload** — a reload terminates and resumes the Claude process, so the guard validates first: if a Workflow, a background subagent, an agent team, or an open tool call is in flight, the reload defers (read-only checkpoint) rather than destroying that work. Tune the near-wall force point with `COZEMPIC_FORCE_RELOAD_PCT` (default `0.88`).\n\n**Reactive overflow recovery** — kqueue/polling file watcher detects inbox-flood overflow within milliseconds, auto-prunes with escalating prescriptions, circuit breaker prevents loops.\n\n**tmux/screen** — reload resumes in the same pane via `send-keys`. Plain terminals open a new window.\n\n**Token thresholds auto-detect** — 200K and 1M models detected automatically. Override with `COZEMPIC_CONTEXT_WINDOW=200000` for Pro plan.\n\n## Behavioral Digest\n\nCozempic extracts your corrections and persists them across compactions:\n\n```bash\n# View extracted rules\ncozempic digest show\n\n# Manually extract from current session\ncozempic digest update\n\n# Sync rules to Claude Code's memory system\ncozempic digest inject\n```\n\n**How it works:**\n- Detects correction signals in your messages (\"don't do X\", \"stop adding Y\", \"always use Z\")\n- All corrections start as \"pending\" and activate after 2 occurrences (prevents one-shot noise from polluting the digest)\n- Rules synced to Claude Code's native memory system (`~/.claude/projects/<cwd>/memory/`)\n- Claude reads these as feedback memories on every turn — they survive compaction natively\n- PreCompact and Stop hooks auto-extract before context is lost\n\n## Agent Teams Protection\n\nWhen Claude's auto-compaction fires, Agent Teams lose coordination state. Cozempic prevents this with five layers:\n\n1. **Continuous checkpoint** — saves team state every N seconds\n2. **Hook-driven checkpoint** — fires after every Task spawn, TaskCreate/Update, before compaction, at session end\n3. **Tiered pruning** — soft threshold trims without disruption; hard threshold does full prune + reload\n4. **Reactive overflow recovery** — detects inbox-flood within milliseconds, auto-recovers (~10s downtime)\n5. **is_protected()** — compact summaries, compact boundaries, content-replacement entries, and behavioral digest messages are never stripped\n\n## Doctor\n\n```bash\ncozempic doctor        # Diagnose issues\ncozempic doctor --fix  # Auto-fix where possible\n```\n\n| Check | What It Detects | Auto-Fix |\n|-------|----------------|----------|\n| `trust-dialog-hang` | Resume hangs on Windows | Reset flag |\n| `claude-json-corruption` | Truncated/corrupted JSON | Restore from backup |\n| `corrupted-tool-use` | `tool_use.name` >200 chars | Parse and repair |\n| `orphaned-tool-results` | `tool_result` missing matching `tool_use` — causes 400 errors | Strip orphans |\n| `zombie-teams` | Stale team directories with dead agents | Remove stale dirs |\n| `oversized-sessions` | Session files >50MB | — |\n| `stale-backups` | Old `.jsonl.bak` files wasting disk | Delete old backups |\n| `disk-usage` | Session storage exceeding healthy thresholds | — |\n\n## Commands\n\n```\ncozempic init                               Wire hooks + slash command into project\ncozempic list                               List sessions with sizes and token estimates\ncozempic current [-d]                       Show/diagnose current session\ncozempic diagnose <session>                 Analyze bloat sources\ncozempic treat <session> [-rx PRESET]       Run prescription (dry-run default)\ncozempic treat <session> --execute          Apply changes with backup\ncozempic strategy <name> <session>          Run single strategy\ncozempic reload [-rx PRESET]                Treat + auto-resume in new terminal\ncozempic checkpoint [--show]                Save team state to disk\ncozempic guard [--daemon]                   Start guard (auto-starts via hook)\ncozempic doctor [--fix]                     Check for known issues\ncozempic digest [show|update|clear|flush|recover|inject]\ncozempic dashboard                          Build a static HTML report of your prune savings\ncozempic self-update                        Upgrade to latest version from PyPI\ncozempic formulary                          Show all strategies & prescriptions\ncozempic uninstall [--project|--all|--purge]  Reverse init: unwire hooks + slash command\n```\n\n## Hook Integration\n\nAfter `cozempic init`, these hooks are wired automatically:\n\n| Hook | When | What |\n|------|------|------|\n| `SessionStart` | Session opens | Guard daemon + digest inject |\n| `PostToolUse[Task]` | Agent spawn | Team checkpoint |\n| `PostToolUse[TaskCreate\\|TaskUpdate]` | Todo changes | Team checkpoint |\n| `PreCompact` | Before compaction | Checkpoint + digest flush |\n| `Stop` | Session end | Checkpoint + digest flush |\n\n## Safety\n\n- **Dry-run by default** — `--execute` required to modify files\n- **Atomic writes** — `write → fsync → os.replace()` — no partial writes\n- **Strict session resolution** — refuses to act on ambiguous matches\n- **Timestamped backups** — automatic `.jsonl.bak` before any modification\n- **is_protected()** — compact summaries, boundaries, marble-origami state, content-replacement, behavioral digest entries are never removed\n- **parentUuid re-linking** — conversation chain integrity maintained after removals\n- **Sibling tool_use protection** — tool_use blocks are kept when their tool_result is kept\n- **Team messages protected** — Task, TaskCreate, SendMessage never pruned\n- **Strategies compose sequentially** — each runs on the output of the previous\n\n## Example Output\n\n```\n  Prescription: aggressive\n  Before: 158.2K tokens (29.56MB, 6602 messages)\n  After:  121.5K tokens (23.09MB, 5073 messages)\n  Freed:  36.7K tokens (23.2%) — 6.47MB, 1529 removed, 4038 modified\n  Context: [============--------] 61%\n\n  Strategy Results:\n    compact-summary-collapse       8.17MB saved (85.2%)  (4201 removed)\n    progress-collapse              1.63MB saved  (5.5%)  (1525 removed)\n    metadata-strip                693.9KB saved  (2.3%)  (2735 modified)\n    tool-use-result-strip          1.44MB saved  (4.9%)  (891 modified)\n    thinking-blocks                1.11MB saved  (3.8%)  (1127 modified)\n    tool-output-trim               1.72MB saved  (5.8%)  (167 modified)\n    ...\n```\n\n## Changelog\n\n### v1.8.23\n\n- **Hardened numeric input validation** — `NaN`, `infinity`, and non-representable huge integers are now rejected with a clear error at every CLI flag, `COZEMPIC_*` env var, and config field (a `NaN` threshold would otherwise silently disable the gate it controls). Thanks to **[@ynaamane](https://github.com/ynaamane)** (#116), and folded in the matching fix for the interactive-guard reload-grace knob\n- **Standing adversarial QA fleet** — `docs/qa-fleet.md` + a corpus-driven regression test so this whole class can't regress\n\n### v1.8.22\n\n- **Interactive \"prune now?\" nudge** — non-blocking heads-up at 25% / 55% / 80% context (once per tier, with hysteresis so it never nags), recommending `cozempic reload`. Brings cozempic's higher-fidelity prune+resume to interactive sessions without surprise reloads. Tunable via `COZEMPIC_NUDGE_PCTS`; silence with `COZEMPIC_NUDGE_OFF=1`\n- **Interactive-safe reload** — warns first, then reloads only at an idle breakpoint (never mid-turn); near the wall (`COZEMPIC_FORCE_RELOAD_PCT`, default 88%) it reloads even mid-turn. Headless/CI behaviour unchanged\n- **Safe-point protection** — the guard never terminates-and-resumes through a running Workflow, background subagent, agent team, or open tool call; the reload defers instead so in-flight work is preserved\n- **Interactivity detection** — `COZEMPIC_INTERACTIVE=auto|on|off`\n- **Efficient idle polling** — exponential poll back-off when the session is quiet (`COZEMPIC_IDLE_BACKOFF_CYCLES`) and skips redundant no-op SOFT checkpoints\n\n### v1.7.1\n\n- **`cozempic reload --session <id|path>`** escape hatch when auto-detect fails in multi-agent sessions. Previously reload had no way to recover from ambiguous session detection, leaving users stuck. Matches `guard --session`.\n- Error message now names the flag to use (was \"use an explicit session ID\" with no instruction on how)\n- **Auto-update message clarified**: after upgrade, says \"active on next run (this process still vX.Y.Z)\" — users no longer think the upgrade failed when `--version` still prints the old number (the running Python process can't hot-swap its own code)\n\n### v1.7.0\n\n- **Telemetry opt-out**: `COZEMPIC_NO_TELEMETRY=1` disables anonymous usage counters\n- **Documented configuration**: `COZEMPIC_NO_AUTO_UPDATE`, `COZEMPIC_NO_TELEMETRY`, `COZEMPIC_CONTEXT_WINDOW` env vars\n\n### v1.6.x\n\n- **4-tier pruning**: soft (25%, no reload) → hard (55%, reload) → emergency (80%, aggressive reload) → user (90%, manual)\n- **Agent-aware reload**: defers reload at 55% when agents are running, forces at 80%\n- **Same-terminal resume**: tmux/screen users get `/exit` + `claude --resume` in the same pane\n- **Clean messaging**: only shows strategies that did something, 1-line hook status output\n- **1M default**: Opus/Sonnet 4.5/4.6 default to 1M context (CC doesn't use `[1m]` suffix)\n- **Auto-upgrade everywhere**: SessionStart hook backgrounds `pip install --upgrade cozempic` on every session. MCP/plugin use `uv run --upgrade`. npm install.js always upgrades.\n- **`cozempic self-update`**: force-upgrade from PyPI regardless of install method (pip, uv, editable, clone)\n- **Auto-updater fixed**: removed TTY check (was blocking hook-triggered updates), tries uv → pip → pipx\n\n### v1.5.0\n\n- **`tool-result-age` strategy** — age-based tool result compaction. Recent results stay verbatim, mid-age get JSON minified and diff context collapsed, old replaced with compact stubs. Claude can re-read any file. 10-40% additional savings targeting the 45% of session size that tool results occupy.\n- 18 strategies total, standard prescription 11, aggressive 18\n- Tests: 273 → 283\n\n### v1.4.0 / v1.4.1\n\n- **Track 1 — Bug fixes**: `is_protected()` guard on all strategies, `isSidechain` preserved in envelope-strip, `output_tokens` in token formula, `parentUuid` re-linking, sibling tool_use protection\n- **Track 2 — New strategies**: `compact-summary-collapse` (85-95%), `attribution-snapshot-strip`, microcompact-aware `tool-output-trim`\n- **Behavioral digest**: extract corrections, sync to Claude Code memory, CLI commands, hook wiring\n- **Context window detection**: MCP server and plugin now auto-detect 200K/1M (was hardcoded 200K)\n- **Cache efficiency metrics**: `cozempic diagnose` shows cache hit rate\n- **transcript_path**: hooks parse session path from payload for faster resolution\n- Tests: 165 → 273\n\n### v1.3.0 / v1.3.1\n\n- Writer-safe live prune + sidecar session store\n- Guard startup cleanup, updater fixes, MCP maintenance\n\n### v1.2.0 — v1.2.8\n\n- Atomic file writes, strict session resolution, schema-first team detection\n- tool-use-result-strip strategy (5-50% on edit-heavy sessions)\n- image-strip strategy (keep last 20%)\n- Auto-update, install tracking, npm package\n- Safety improvements: SIGTERM handler, backup cleanup, permission error handling\n\n## Configuration\n\n| Variable | Default | Effect |\n|----------|---------|--------|\n| `COZEMPIC_CONTEXT_WINDOW` | auto-detect | Override context window size (e.g. `200000` for Pro plan) |\n| `COZEMPIC_NO_AUTO_UPDATE` | off | Disable all automatic upgrades (honored by the Python updater, SessionStart hook, and npm installer). Not generally recommended — Claude Code ships frequent changes and cozempic updates keep strategies compatible with the latest session format. See [Auto-update & how to control it](#auto-update--how-to-control-it). |\n| `COZEMPIC_PIN` | unset | Hold a reviewed version (e.g. `1.8.30`): disables auto-update on both paths and warns on drift instead of auto-installing. For users who want the protection on a version they've vetted. |\n| `COZEMPIC_NO_TELEMETRY` | off | Skip anonymous usage counters. Cozempic pings a simple counter on each prune — no personal data, session content, or identifiable information is sent. Helps us prioritize development. |\n\n## Contributing\n\nContributions welcome. To add a strategy:\n\n1. Create a function in the appropriate tier file under `src/cozempic/strategies/`\n2. Decorate with `@strategy(name, description, tier, expected_savings)`\n3. Return a `StrategyResult` with a list of `PruneAction`s\n4. Add to the appropriate prescription in `src/cozempic/registry.py`\n\n## License\n\nMIT — see [LICENSE](LICENSE).\n\nBuilt by [Ruya AI](https://ruya.ai).\n"}