{"id":48085194,"url":"https://github.com/Ruya-AI/cozempic","last_synced_at":"2026-04-20T01:00:44.337Z","repository":{"id":336827369,"uuid":"1151288796","full_name":"Ruya-AI/cozempic","owner":"Ruya-AI","description":"Context cleaning for Claude Code — prune bloated sessions, protect Agent Teams from context loss, auto-guard with tiered pruning","archived":false,"fork":false,"pushed_at":"2026-04-15T13:21:41.000Z","size":443,"stargazers_count":244,"open_issues_count":6,"forks_count":15,"subscribers_count":3,"default_branch":"main","last_synced_at":"2026-04-15T15:26:24.293Z","etag":null,"topics":["agent-teams","claude-code","claude-skills","cli","context","context-management","jsonl","llm-tools","pruning","python","session-management"],"latest_commit_sha":null,"homepage":"https://pypi.org/project/cozempic/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Ruya-AI.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-02-06T09:27:56.000Z","updated_at":"2026-04-15T13:21:46.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/Ruya-AI/cozempic","commit_stats":null,"previous_names":["junaidtitan/cozempic"],"tags_count":50,"template":false,"template_full_name":null,"purl":"pkg:github/Ruya-AI/cozempic","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Ruya-AI%2Fcozempic","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Ruya-AI%2Fcozempic/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Ruya-AI%2Fcozempic/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Ruya-AI%2Fcozempic/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Ruya-AI","download_url":"https://codeload.github.com/Ruya-AI/cozempic/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Ruya-AI%2Fcozempic/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32028547,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-20T00:18:06.643Z","status":"ssl_error","status_checked_at":"2026-04-20T00:17:31.068Z","response_time":55,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agent-teams","claude-code","claude-skills","cli","context","context-management","jsonl","llm-tools","pruning","python","session-management"],"created_at":"2026-04-04T15:14:13.314Z","updated_at":"2026-04-20T01:00:44.329Z","avatar_url":"https://github.com/Ruya-AI.png","language":"Python","funding_links":[],"categories":["Plugins"],"sub_categories":["All Plugins"],"readme":"# Cozempic\n\n![Downloads](https://img.shields.io/badge/downloads-35k%2B-brightgreen) ![Version](https://img.shields.io/badge/version-1.8.0-blue) ![License](https://img.shields.io/badge/license-MIT-lightgrey)\n\n**35,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 **17 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- **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- **8 doctor checks** — diagnose and auto-fix session corruption, orphaned tool results, zombie teams\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- **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:\n\n```bash\n# pip (Python ≥ 3.10)\npip install cozempic\n\n# pipx — isolated user install, always available on PATH\npipx install cozempic\n\n# uv / uvx — no install needed, run on demand\nuvx cozempic --help\n\n# Homebrew (macOS / Linux)\nbrew install Ruya-AI/cozempic/cozempic\n\n# Nix flake\nnix profile install github:Ruya-AI/cozempic?dir=packaging/nix\n```\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\nThen one-time setup:\n\n```bash\ncozempic init\n```\n\nThat's it. The guard daemon auto-starts on every session via hooks. No second terminal needed.\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 \u003csession_id\u003e -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 \u0026 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 (\u003e8KB or \u003e100 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 (deferred if agents active) |\n| Emergency | 80% | aggressive prune | Yes (forced) |\n| User | 90% | manual aggressive | Yes |\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- Explicit corrections activate immediately; implicit corrections need 2 occurrences\n- Rules synced to Claude Code's native memory system (`~/.claude/projects/\u003ccwd\u003e/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` \u003e200 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 \u003e50MB | — |\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 \u003csession\u003e                 Analyze bloat sources\ncozempic treat \u003csession\u003e [-rx PRESET]       Run prescription (dry-run default)\ncozempic treat \u003csession\u003e --execute          Apply changes with backup\ncozempic strategy \u003cname\u003e \u003csession\u003e          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 self-update                        Upgrade to latest version from PyPI\ncozempic formulary                          Show all strategies \u0026 prescriptions\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.7.1\n\n- **`cozempic reload --session \u003cid|path\u003e`** 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 | Skip automatic version checks. Not recommended — Claude Code ships frequent changes and cozempic updates keep strategies compatible with the latest session format. |\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","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FRuya-AI%2Fcozempic","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FRuya-AI%2Fcozempic","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FRuya-AI%2Fcozempic/lists"}