Cozempic

repository·main·Indexed 43 days ago

https://github.com/ruya-ai/cozempic

A context management tool for Claude Code that prunes session bloat—such as metadata, progress ticks, and large tool outputs—to keep API calls lean and prevent context loss. Version 1.8.39 features a guard daemon for proactive pruning, MCP tools for token monitoring, and a behavioral digest to persist user preferences. It integrates with Claude Code via slash command skills, lifecycle hooks, and an MCP server.

Tokens
29.1K
Snippets
94
Records
137
Agent score
57%

What's inside Cozempic

  1. How Cozempic integrates with Claude Code

    main

    Cozempic operates through three distinct layers of integration:

    1. Skills: These are slash commands that call the cozempic CLI commands via Bash.
    2. Hooks: These automate lifecycle management by running cozempic guard and cozempic checkpoint during specific Claude Code events.
    3. MCP Server: This provides deep integration by importing directly from the cozempic Python package, allowing Claude to use rich tools for session management.
  2. How Cozempic hook integration works

    main

    After running cozempic init, the following hooks are automatically wired into your session to ensure coordination state is preserved and context is managed:

    HookWhenWhat
    SessionStartSession opensGuard daemon + digest inject
    PostToolUse[Task]Agent spawnTeam checkpoint
    PostToolUse[TaskCreate|TaskUpdate]Todo changesTeam checkpoint
    PreCompactBefore compactionCheckpoint + digest flush
    StopSession endCheckpoint + digest flush
  3. How the Guard Daemon works

    main

    The guard daemon monitors your Claude Code session and prunes context automatically based on usage thresholds. It uses a 4-tier proactive pruning model:

    TierThresholdActionReload?
    Soft25%gentle file cleanupNo
    Hard55%standard pruneYes (interactive: at a breakpoint; deferred if agents active)
    Hard280%aggressive pruneYes (gated by the safe-point check)
    User90%manual aggressiveYes

    Key Safety Features:

    • Safe-point protection: The guard defers reloads if a Workflow, background subagent, agent team, or open tool call is in flight.
    • Interactive-safe reload: In interactive sessions, the guard provides a non-blocking nudge and reloads only at an idle breakpoint to avoid interrupting mid-turn work.
    • Token detection: Automatically detects 200K and 1M context windows. Use COZEMPIC_CONTEXT_WINDOW=200000 to override.
  4. Manage the Behavioral Digest

    main

    The Behavioral Digest extracts user corrections (e.g., "don't do X") from the conversation and persists them to Claude Code's native memory system (~/.claude/projects/<cwd>/memory/). This ensures your preferences survive context compaction.

    # View extracted rules
    cozempic digest show
    
    # Manually extract from current session
    cozempic digest update
    
    # Sync rules to Claude Code's memory system
    cozempic digest inject
  5. How rules are injected into the agent session

    main

    Rules are injected into the agent's context via a synthetic user turn appended to the end of the conversation history (tail position). This ensures they receive high attention weight.

    Injection Events:

    • SessionStart hook: Injects all hard and soft rules.
    • PostCompact hook: Re-injects rules immediately after context compaction.
    • Contract update detected: Injects only the delta (new/changed rules) if the file's modification time has changed.

    Injection Format: The injected block is wrapped in a protected marker <!-- __cozempic_behavioral_digest__: true --> to prevent the agent from stripping or modifying it.

    Example Injected JSONL Structure:

    {
      "type": "user",
      "message": {
        "role": "user",
        "content": "<!-- __cozempic_behavioral_digest__: true -->\n[BEHAVIORAL CONTRACT]\n\n**Always apply:**\nDo not add Co-Authored-By lines to git commit messages.\n\n**Apply when working with files:**\nDo not use the Write tool to modify existing files — use Edit.\n\n[End of behavioral contract — Cozempic v1.x]"
      }
    }
  6. L0 — Harness-contract / marker drift

    main

    The safety gate relies on hardcoded tool names, input keys, and result-string markers. If these drift, the gate may silently fail to recognize activity, leading to dangerous reloads during live work.

    Defenses against Marker Drift:

    1. Ground-truth literals: Verify every marker against REAL transcripts (e.g., grep ~/.claude/projects). Test casing and key variants (e.g., camelCase vs snake_case, to vs agentId).
    2. Real Fixtures: Use redacted REAL fixtures in tests/fixtures/harness/ rather than purely synthetic ones.
    3. Deny-by-default: If a coordination signal cannot be resolved, the gate must BLOCK, not reload. A matcher should fail toward "block".

    Avoiding Over-blocking (The Dual-Failure Surface):

    • Correlate, don't trust bare text: A spawn marker should only count if it is inside a tool_result whose paired tool_use is a spawn tool (e.g., Agent, Task, TeamCreate, SpawnTeammate).
    • Require structure: Match the actual <teammate-message ... teammate_id="..."> carrier on its delivery surface, not bare tokens in user messages.
    • Scope state transitions: On ambiguity during a TeamDelete, leave members as a recoverable wedge rather than performing a clear-all (which acts as an unrecoverable SIGKILL).
    standing test: `tests/test_reload_gate_contract.py`
  7. Design principles for effective behavioral rules

    main

    Based on research into instruction following and attention models, effective behavioral rules (contracts) should follow these constraints to avoid degradation in model performance:

    • Use Prohibitions over Aspirations: Models follow negative constraints much better than positive ones. Instead of "Be concise", use "Do not add unnecessary text to your response".
    • Maintain a Minimum Viable Ruleset: Avoid instruction bloat. Having ~30 irrelevant rules causes measurable degradation. A hard cap of ≤ 20 rules is recommended to maintain high compliance.
    • Prefer Natural Language: Use short, specific natural language directives rather than formal logic or structured schemas.
    • Tail-Position Injection: To avoid the "Lost in the Middle" accuracy drop, rules should be injected at the tail (most recent part) of the context rather than the head.
    • Include Before/After Context: For higher reliability, store rules as explicit contrasts (e.g., "I did X, correction was Y, rule is Z") rather than just the distilled rule.
  8. Understanding the Behavioral Digest concept

    main

    The Behavioral Digest is a design mechanism for Cozempic intended to solve the 'behavioral state persistence' problem in Claude Code.

    While standard compaction (summarization) preserves code changes and decisions, it often discards mid-session behavioral corrections (e.g., "don't do X"), repeated failure patterns, and session-specific learned facts. The Behavioral Digest aims to extract these corrections, rules, gates, and project-specific facts from the session JSONL and re-inject them at the high-attention tail position of the context window. This ensures they survive compaction and session resumption, transforming Cozempic from a simple context pruning tool into a session continuity platform.

  9. Classify user turns for rule extraction

    main

    To determine if a user interaction should result in a new rule, turns are classified into one of six categories. This classification helps distinguish between permanent behavioral changes and temporary task-specific constraints.

    CategoryDescription
    EXPLICIT_CORRECTIONUser directly states the agent was wrong or provides replacement output.
    IMPLICIT_CORRECTIONUser rephrases a prompt with added constraints or completes the task themselves.
    PREFERENCEProactive declaration of style, format, or approach (no prior failure).
    CLARIFICATIONResolves ambiguity; either the agent asked or the user volunteered context.
    ONE_OFFTask-scoped only (e.g., "just this once"). These should not be persisted.
    NONENormal turn with no feedback signal.

    Persistence Logic:

    • session: Rules that apply to the current project/session.
    • persistent: Rules that apply across all projects (user-scoped).
    Classify this user turn in the conversation. Choose one:
    EXPLICIT_CORRECTION | IMPLICIT_CORRECTION | PREFERENCE | CLARIFICATION | ONE_OFF | NONE
    
    ... [Examples provided in prompt] ...
    
    Turn to classify: "[TURN]"
    Classification:
    Reasoning (one sentence):
    Persistence: session | persistent
  10. Understand the Behavioral Digest contract format

    main

    The Behavioral Digest is a persistent contract used to store behavioral rules for an AI agent. It is stored in a Markdown file and follows a specific structure to manage rules by priority and scope.

    Storage Locations:

    • Project-local (Recommended): .cozempic/behavioral-digest.md (takes precedence for project-specific corrections).
    • User-global: ~/.cozempic/behavioral-digest.md.

    Rule Classifications:

    • Hard Rules: Always injected into the agent's context. Used for zero-tolerance corrections (e.g., git operations).
    • Soft Rules: Injected only when the current session scope is relevant (e.g., file operations).
    • Pending Rules: Rules with fewer than 3 occurrences that are under observation before being promoted to Active.

    Rule Structure: Each rule includes metadata such as Priority, Source, Importance, Scope, and a Rule definition using prohibition framing (e.g., "Do not [X]").

    # Behavioral Digest
    <!-- cozempic: behavioral-digest v1 -->
    <!-- project: /path/to/project -->
    <!-- updated: 2026-03-31T14:23:00Z -->
    <!-- session: <session_id_that_last_updated> -->
    
    ## Active Rules — Hard (always injected)
    
    ### [R001] No Co-Authored-By commits
    **Priority**: HARD
    **Source**: User correction (3 occurrences)
    **First seen**: 2026-03-15 | **Last reinforced**: 2026-03-30
    **Importance**: 5 (3 corrections + 2 upvotes)
    **Scope**: git operations
    **Rule**: Do not add "Co-Authored-By" lines to git commit messages.
    **Before**: Added `Co-Authored-By: Claude Sonnet <noreply@anthropic.com>` to commit
    **After**: User deleted that line from the commit message
    **Signal**: I added Co-Authored-By because default behavior includes it; user treats this project's commits as single-author.
    **Trigger**: Any git commit operation
    
    ## Active Rules — Soft (injected by scope relevance)
    
    ### [R002] Edit not Write for existing files
    **Priority**: SOFT
    **Source**: User correction (2 occurrences)
    **First seen**: 2026-03-20 | **Last reinforced**: 2026-03-28
    **Importance**: 2
    **Scope**: file operations
    **Rule**: Do not use the Write tool to modify existing files — use Edit. Only use Write for new files.
    **Before**: Used Write tool to replace entire file content
    **After**: User said "use Edit not Write"
    **Signal**: I used Write because the change was large; user prefers surgical edits.
    **Trigger**: Any file modification operation on existing files
    
    ## Pending Rules (< 3 occurrences, under observation)
    
    ### [P001] Prefer uv over pip
    **Priority**: SOFT (pending)
    **Source**: User correction (1 occurrence)
    **First seen**: 2026-03-31
    **Importance**: 1
    **Rule**: Use uv instead of pip for package operations in this project.
    **Before**: Suggested `pip install ...`
    **After**: User said "we use uv"
    **Trigger**: Any package installation or management command
  11. Maintain and prune the Behavioral Digest contract

    main

    The Behavioral Digest uses an AutoRefine model to ensure the ruleset remains effective and doesn't exceed a hard cap of 20 active rules.

    Promotion Logic:

    • Rules move from Pending to Active once they reach 3 occurrences.
    • A composite confidence score (based on evidence count, source reliability, recency, and type prior) must meet a threshold of 0.55 for admission.

    Importance Scoring (ExpeL model):

    • +1: Per correction occurrence.
    • +1: Per explicit user reinforcement (UPVOTE).
    • -1: Per "this is no longer needed" signal (DOWNVOTE).

    Pruning Rules:

    • Delete active rules with importance <= 0.
    • Move active rules to Pending if they haven't been seen in 30+ days and have importance <= 1.
    • Merge duplicates with semantic similarity $> 0.85$.

    Enforcing the Hard Cap: When the limit of 20 active rules is reached, new promotions require either removing the lowest-importance rule or merging with a similar existing rule.

  12. Understand Cozempic Pruning Strategies and Prescriptions

    main

    Cozempic uses 18 composable strategies categorized into three prescription tiers. Strategies range from 'gentle' (removing metadata and progress ticks) to 'aggressive' (stripping images and collapsing HTTP spam).

    | Prescription | Strategies | Risk | Typical Savings |
    |---|---|---|---|
    | `gentle` | 5 | Minimal | 85-95% (with compact boundary) |
    | `standard` | 11 | Low | 25-45% |
    | `aggressive` | 18 | Moderate | 35-60% |