New:Introducing Socket Scanning for VS Code Marketplace Extensions.Learn more →
Get Started

claude-code-optimizer

Package Overview
Dependencies
Maintainers
1
Versions
19
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

claude-code-optimizer

Optimize Claude Code token usage with smart rules, skills, hooks, and context templates

latest
Source
npmnpm
Version
4.0.3
Version published
Weekly downloads
0
Maintainers
1
Weekly downloads
 
Created
Source

Claude Code Optimizer

Stop burning tokens. Start shipping faster.

npm version npm downloads GitHub stars License: MIT GitHub forks

The #1 toolkit to make Claude Code faster, cheaper, and smarter. 25 skills | 6 rules | 13 hooks | 2 templates — one install.

Get Started | What's New in v4 | Skills | Author

Built by Huzefa Nalkheda Wala — AI Product Engineer & Medical AI Researcher

Website GitHub LinkedIn HuggingFace Medium

The Problem

Every Claude Code session starts the same way — Claude explores your codebase from scratch. It runs 15-40 tool calls just to orient itself, re-reads the same files, misses your conventions, and burns tokens on discovery instead of doing actual work.

You're paying for exploration, not engineering.

The Fix

Claude Code Optimizer gives Claude a compass instead of a GPS — a layered context system that loads just enough structure, only when relevant.

Without OptimizerWith Optimizer
Tool calls per task~20-40~5-10
Session startFull explorationTargeted reads
ConventionsNo awarenessFollows your patterns
ArchitectureRe-discovers every timeKnows the map
Session memoryForgets everythingRemembers last session
Always-on token overheadUnbounded~300 tokens

One install. Zero config. Immediate savings.

What's New in v4

FeatureWhat It Does
Two-Stage Code Review/review now checks spec compliance first, then code quality — "Did you build the right thing?" before "Did you build it well?"
Anti-Rationalization/tdd, /review, and /security-scan now include iron laws, excuse tables, and loophole closure — inspired by obra/superpowers
Progressive Disclosure/explore-area uses 3 layers (file index -> entry points -> deep dive) for ~10x token savings on exploration
Persistent Session MemorySession summaries saved to ~/.claude/sessions/ and injected on next start — Claude remembers what you worked on last
Subagent-Driven Development/subagent-dev dispatches fresh subagents per task with two-stage review — controller never writes code directly
Git Worktree Isolation/worktree creates isolated workspaces for safe development with verified test baselines
Optimization Modes/mode aggressive|balanced|thorough — tune token-saving behavior for the task at hand
Auto-Upgradenpm i -g claude-code-optimizer@latest now auto-detects version changes and updates all files seamlessly
CSO-Optimized DescriptionsAll 25 skill descriptions rewritten as triggering conditions — Claude discovers the right skill more reliably
Plugin Marketplace.claude-plugin/ manifest added for plugin marketplace discovery

Quick Start

Install it — everything sets up automatically.

npm (Windows, Mac, Linux)

npm i -g claude-code-optimizer

That's it. Skills, rules, hooks, and templates are installed to ~/.claude/ automatically.

Upgrading from v3?

Just reinstall — the installer auto-detects your old version and updates everything:

npm i -g claude-code-optimizer@latest

All your skills, hooks, rules, and settings are updated seamlessly. Or force-update anytime:

npx claude-code-optimizer --update

curl (Mac, Linux, WSL)

curl -sL https://raw.githubusercontent.com/huzaifa525/claude-code-optimizer/main/scripts/install.sh | bash

PowerShell (Windows — no Node.js needed)

irm https://raw.githubusercontent.com/huzaifa525/claude-code-optimizer/main/scripts/install.ps1 | iex

Uninstall

# npm
npx claude-code-optimizer --uninstall

# curl
curl -sL https://raw.githubusercontent.com/huzaifa525/claude-code-optimizer/main/scripts/uninstall.sh | bash

Post-Install

Copy the templates to your project and fill in your details:

cp ~/.claude/CLAUDE.md.template ./CLAUDE.md
cp ~/.claude/claudeignore.template ./.claudeignore

What You Get

TypeCountInstalled ToPurpose
Skills25~/.claude/skills/Slash commands for every workflow
Rules6~/.claude/rules/Path-scoped conventions that auto-load
Hooks13~/.claude/hooks/Automation scripts that run on their own
Templates2~/.claude/CLAUDE.md + .claudeignore starters
Sessions-~/.claude/sessions/Persistent memory across restarts

Skills (25 Slash Commands)

Skills are commands you invoke inside Claude Code with /skill-name. They run as specialized prompts that guide Claude to work smarter.

Exploration & Context

SkillPurposeHow to Invoke
/explore-areaDeep codebase exploration with progressive disclosure/explore-area src/api/
/gen-contextGenerate fresh project context summary/gen-context
/onboardFull onboarding guide for new developers/onboard
/token-checkSession token usage analysis/token-check
/optimize-tokensWeb search for latest optimization tips + project analysis/optimize-tokens

Development Workflow

SkillPurposeHow to Invoke
/planningPersistent markdown planning for complex tasksAuto-activates on complex tasks
/planCreate implementation plan with task breakdown/plan Add user notifications
/smart-editPattern-aware code changes/smart-edit Add delete endpoint
/tddTest-Driven Development with anti-rationalization/tdd user login validation
/fix-issueFetch GitHub issue, implement fix, test, commit/fix-issue 42
/debug-errorAnalyze error, find root cause, fix/debug-error Cannot read property of undefined
/refactorRefactor code while preserving behavior/refactor auth middleware
/migrateMigrate between frameworks/versions/migrate React-Router-v5 React-Router-v6
/worktreeIsolated git worktree for safe development/worktree user-notifications
/subagent-devDispatch fresh subagents per task with review/subagent-dev

Git & GitHub

SkillPurposeHow to Invoke
/commitGenerate conventional commit message and commit/commit
/create-prCreate PR with auto-generated description/create-pr
/changelogGenerate changelog from git history/changelog

Code Quality & Security

SkillPurposeHow to Invoke
/reviewTwo-stage review: spec compliance then code quality/review
/security-scanOWASP top 10, secrets, injection scan with anti-rationalization/security-scan
/perf-checkN+1 queries, memory leaks, bundle size analysis/perf-check src/api/
/dep-checkOutdated/vulnerable dependency check/dep-check
/documentGenerate docs/JSDoc/docstrings/document src/utils/

Optimization

SkillPurposeHow to Invoke
/modeSwitch optimization mode (aggressive/balanced/thorough)/mode aggressive
/setupAuto-generate CLAUDE.md and .claudeignore for project/setup

Skill Deep Dives

/explore-area [directory] — Progressive disclosure exploration

Uses a 3-layer approach to minimize token cost:

  • Layer 1 (File Index) — List files without reading contents. Often enough.
  • Layer 2 (Entry Points) — Read index files and grep for exports/signatures.
  • Layer 3 (Deep Dive) — Read full files only where needed, with offset/limit.

Runs in a forked subagent so exploration tokens don't pollute your main context.

/explore-area src/api/
/explore-area src/components/

Example output:

## Area: src/api/

### Structure (12 files)
- routes/index.ts → route registration
- middleware/auth.ts → JWT validation

### Patterns to Follow
- One file per resource in routes/
- Zod validation at route level

### Gotchas
- auth middleware is duplicated intentionally (different token validation)
/review — Two-stage code review

Stage 1: Spec Compliance — Does the code do what was intended? Checks intent against implementation, verifies all requirements are met, confirms correct files were modified. Must pass before Stage 2.

Stage 2: Code Quality — Is the code well-written? Checks security, performance, code quality, and convention compliance.

Includes anti-rationalization: a table of common excuses ("this is just a small change") with rebuttals ("small changes cause big bugs"). Runs in a forked subagent.

/tdd [feature] — Test-Driven Development with iron laws

Strict RED-GREEN-REFACTOR with three iron laws:

  • No production code without a failing test. Write code before test? DELETE it.
  • Write MINIMUM code to pass. If the test passes, STOP.
  • Delete means delete. Don't keep as reference. Don't adapt it. Don't look at it.

Includes anti-rationalization table for common TDD excuses.

/tdd user login validation
/worktree [branch-name] — Isolated git worktree development

Creates a git worktree for safe, isolated development:

  • Verifies clean baseline (no uncommitted changes)
  • Creates worktree on a new branch
  • Runs tests BEFORE any changes to verify baseline
  • All work happens in isolation
  • Presents merge/PR/keep/discard options when done
/worktree user-notifications
/worktree fix-auth-bug
/subagent-dev — Dispatch fresh subagents per task

Inspired by obra/superpowers. The controller (Claude) coordinates but never writes code directly:

  • Load the plan (from task_plan.md or user's task list)
  • For each task: dispatch implementer subagent → spec reviewer → quality reviewer
  • Handle status: DONE, DONE_WITH_CONCERNS, NEEDS_CONTEXT, BLOCKED
  • Verify all tests pass at the end

Each subagent gets fresh context — no pollution from previous tasks.

/mode [aggressive|balanced|thorough] — Optimization profiles
ModeThinking BudgetBest For
Aggressive4K tokensRoutine edits, simple bug fixes
Balanced10K tokensGeneral development (default)
Thorough32K tokensComplex debugging, architecture, security
/mode aggressive   # maximum savings
/mode thorough     # maximum context
/mode balanced     # back to default
/security-scan — OWASP vulnerability scan with anti-rationalization

Scans for OWASP top 10 vulnerabilities — hardcoded secrets, SQL injection, XSS, command injection, missing auth, insecure configs, dependency vulnerabilities. Returns a severity-ranked report.

Iron Law: No "probably safe." Verify or flag. False positives are cheap. Missed vulnerabilities are not.

Includes anti-rationalization for common security excuses ("this is internal code", "we're behind a firewall", "we'll fix it later"). Runs in a forked subagent.

/gen-context — Fresh project context in seconds

Analyzes package.json, project structure, entry points, framework, git history, and existing CLAUDE.md. Gives Claude a full picture without you explaining it.

/gen-context
/smart-edit [what to change] — Pattern-aware code changes

Before making any change, it finds similar existing code in your codebase, reads at least 2 examples of the same pattern, checks conventions, then implements matching your exact style.

/smart-edit Add a delete endpoint for users
/smart-edit Add dark mode toggle to settings page
/smart-edit Create a new database migration for adding email field
/token-check — Session health report

Analyzes your current session for token efficiency — context usage, MCP servers, conversation length, and optimization tips.

/token-check

Example output:

Session Health Report
---------------------
Context usage: ~120K / 200K
Conversation turns: 23
Suggested action: /compact
Optimization tips:
- 3 files read multiple times (users.ts, auth.ts, db.ts)
- 2 MCP servers unused this session
- CLAUDE.md is 340 lines (recommend < 200)
/planning — Persistent task tracking

Automatically creates task_plan.md for complex tasks. Breaks work into steps, tracks progress with checkboxes, and survives across sessions. Auto-activates when a task requires 5+ steps.

/commit — Smart conventional commits

Analyzes staged changes (git diff --cached), checks your recent commit style, and generates a conventional commit message (feat:, fix:, refactor:, etc.). Stage your changes with git add, then type /commit.

/create-pr — Auto-generated PRs

Analyzes ALL commits on your branch (not just the latest), generates a PR title, summary bullets, change list, and test plan checklist. Pushes and creates the PR via gh.

/fix-issue [number] — End-to-end issue resolution

Fetches a GitHub issue, creates a branch, finds relevant code, implements the fix, writes tests, runs them, and commits with the issue number.

/fix-issue 42
/debug-error [error] — Root cause analysis

Parses an error message or stack trace, traces the root cause through the codebase, checks recent git changes, implements a fix, and verifies.

/refactor [target] — Safe refactoring

Runs tests first to establish a baseline, then refactors incrementally. After each change, runs tests again. If anything breaks, reverts immediately.

/perf-check [target] — Performance analysis

Analyzes for N+1 queries, memory leaks, unnecessary re-renders, large bundle imports, missing caching, O(n^2) algorithms, and more. Runs in a forked subagent.

/dep-check — Dependency audit

Runs npm audit / pip audit, checks for outdated packages, flags deprecated dependencies, and suggests upgrades with breaking change warnings.

/changelog — Auto-generated changelogs

Generates a changelog from git history since the last tag. Groups commits by type (features, fixes, breaking changes). Outputs or updates CHANGELOG.md.

/migrate [from] [to] — Framework migration

Greps for all usages of the old API/library, creates a migration plan, applies changes file by file, runs tests after each file, and reports what couldn't be auto-migrated.

/migrate Express-v4 Express-v5
/migrate React-Router-v5 React-Router-v6
/onboard — New developer guide

Generates a complete onboarding guide — project structure, tech stack, dev workflow, code conventions, common tasks, environment variables, and useful commands. Runs in a forked subagent.

/plan [feature] — Implementation planning

Creates a phased implementation plan with task breakdown, file mapping, reference code pointers, dependencies, and risk assessment. Runs in a forked subagent using the Plan agent.

/optimize-tokens — Token optimization tips

Searches the web for the latest Claude Code token optimization tips, then analyzes your current project setup (CLAUDE.md size, .claudeignore, rules, skills, MCP servers, settings). Returns a scored report with quick wins.

Rules (Path-Scoped Guidelines)

Rules are markdown files in ~/.claude/rules/ that give Claude persistent context about your coding conventions. They use path-scoping — each rule only loads when Claude reads files matching specific patterns, so you don't waste tokens on irrelevant context.

RuleActivates When Claude ReadsWhat It Tells Claude
frontend.mdsrc/components/**, src/pages/**, **/*.tsx, **/*.jsxComponent structure, styling approach, patterns to follow, what NOT to do
backend.mdsrc/api/**, src/routes/**, src/controllers/**, src/services/**API structure (routes -> controllers -> services), endpoint patterns, error handling
database.mdsrc/database/**, src/models/**, prisma/**, **/*.sqlORM usage, migration rules, query patterns, safety rules
testing.md**/*.test.*, **/*.spec.*, tests/**Test runner, file conventions, what to test, what NOT to test
skill-router.mdAlways activeMaps user intents to skills — "commit this" -> /commit, "review" -> /review, etc.
token-optimization.mdAlways activeThinking caps, model selection, compaction strategy, duplicate read prevention

How it works: You edit these files with your actual conventions. When Claude opens a .tsx file, frontend.md loads automatically. When Claude is working on backend code, frontend rules stay hidden — zero token cost.

How to customize rules

# Edit any rule
code ~/.claude/rules/frontend.md

# Add a new rule
code ~/.claude/rules/security.md

Add paths: frontmatter to scope when it loads:

---
paths:
  - "src/api/**"
  - "**/*.ts"
---

Your rules here...

Hooks (Automation Scripts)

Hooks are shell scripts that run automatically at specific moments in Claude Code's lifecycle. They don't need to be invoked — they trigger on their own.

HookTriggers OnWhat It Does
generate-context.shEvery session startInjects recent commits, uncommitted changes, branch into context
memory-inject.shEvery session startInjects last session's summary for persistent memory across restarts
resume-plan.shEvery session startDetects task_plan.md and injects it so /planning continues across sessions
auto-setup.shEvery session startAuto-generates CLAUDE.md and .claudeignore if missing — detects stack, framework, entry points
auto-update-check.shEvery session start (once/day)Checks for new optimizer version and notifies you
protect-files.shEvery file edit/writeBlocks edits to .env, credentials, lock files, .git/, private keys
block-dangerous.shEvery bash commandBlocks rm -rf /, git push --force main, DROP TABLE, etc.
auto-format.shAfter every file editAuto-runs prettier/black/gofmt/rustfmt on edited files
filter-test-output.shAfter test/build/lint commandsFilters verbose output (50+ lines) to summary only
track-activity.shAfter every tool useLightweight activity logger for session awareness
commit-reminder.shWhen Claude stops respondingReminds about uncommitted changes, suggests /commit
session-summary.shWhen Claude stops respondingCaptures what was accomplished and saves to ~/.claude/sessions/
token-savings-footer.shEvery 5th responseShows estimated token savings this session
Hook details

Persistent Session Memory

Three hooks work together to give Claude memory across sessions:

  • track-activity.sh (PostToolUse) — Logs tool usage timestamps during the session
  • session-summary.sh (Stop) — Captures git changes, commits, and activity count into ~/.claude/sessions/
  • memory-inject.sh (SessionStart) — Injects the last session's summary so Claude knows what you worked on

No database needed — just lightweight markdown files.

protect-files.sh

Prevents accidental edits to files that should never be touched by AI.

CategoryFiles
Environment.env, .env.local, .env.production
Credentialscredentials.json, *.pem, *.key
Lock filespackage-lock.json, yarn.lock, pnpm-lock.yaml
Git.git/ directory

filter-test-output.sh

Test output can be thousands of lines. This saves massive token waste by only feeding Claude the information it actually needs (what passed, what failed). Full output stays in your terminal.

How to activate hooks

Add to your project's .claude/settings.json:

{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "",
        "hooks": [
          { "type": "command", "command": "bash ~/.claude/hooks/generate-context.sh" },
          { "type": "command", "command": "bash ~/.claude/hooks/memory-inject.sh" }
        ]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "bash ~/.claude/hooks/protect-files.sh" }
        ]
      }
    ]
  }
}

How It All Works Together

StageWhat HappensToken Cost
Session Startgenerate-context.sh + memory-inject.sh — Claude sees recent commits, changes, branch, and last session~300
Always LoadedCLAUDE.md loads — Claude sees commands, entry points, flow diagrams, decisions~200
Always Active.claudeignore blocks node_modules, dist, lock files, .env from being read0
On-DemandRules load based on what files Claude reads (frontend.md, backend.md, etc.)~500 when active
Auto Planningplanning skill activates on complex tasks — creates task_plan.md~200
User Invoked25 skills for commits, reviews, PRs, debugging, security, worktrees, etc.0 in main context (forked)
Every Editprotect-files.sh guards .env, credentials, lock files~10
Session Endsession-summary.sh saves what was accomplished for next session0 (background)

Total always-on overhead: ~500 tokens. Everything else loads only when needed.

Optimization Strategies

StrategyToken SavingsEffort
Lean CLAUDE.md with entry points~30%Low
Path-scoped rules~20%Medium
.claudeignore~15%Low
Progressive disclosure exploration (forked)~25%Low
Session start hooks + memory~10%Medium
Code annotations (@claude tags)~15%Medium
/mode aggressive~40%Low
Anti-rationalization in skills~10%Low

Stack Templates

The examples/ directory includes ready-to-use CLAUDE.md templates for popular stacks:

StackFrameworkKey Features
Next.js AppNext.js 14, App RouterServer Actions, Prisma, Tailwind
Express APIExpress.jsREST, Controllers, Services, JWT Auth
Python FastAPIFastAPISQLAlchemy, Alembic, Pydantic v2
MonorepoTurborepopnpm workspaces, shared packages

Browse them on GitHub.

Star History

Star History Chart

If this tool saves you tokens (and money), consider giving it a star — it helps others find it too.

Contributing

We welcome contributions! Whether it's a new skill, a stack-specific template, or a bug fix:

  • Fork the repo
  • Create your feature branch
  • Submit a PR

See CONTRIBUTING.md for details.

Meet the Author

Huzefa Nalkheda Wala

AI Product Engineer | Medical AI Researcher | Open Source Builder

Building enterprise AI systems at Ruby CRM / CleverFlow (Dubai) — 45+ production features shipped with 99.5% uptime. Passionate about making AI-assisted development faster and more accessible for every developer.

Websitehuzefanalkhedawala.in
GitHub@huzaifa525
LinkedInhuzefanalkheda
HuggingFacehuzaifa525
Mediumhuzefanalkheda
npmclaude-code-optimizer

Other projects: Check out my GitHub for more AI/ML tools and research.

If Claude Code Optimizer saves you time and money, star the repo and share it with your team.

MIT License -- Huzefa Nalkheda Wala

Keywords

claude

FAQs

Package last updated on 30 Mar 2026

Related posts