SLOPSHOPPER

context-meter

Band above the prompt: context fill, cache read, cost, plan limits; warns at 50%/70%; Handoff button and /handoff past 70%.

newbandcommandtoast
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · context-meter
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /meter ⎿ context-meter: Meter hidden. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

claude-code-kit

Formerly ai-prompts. Old links and clones redirect to this repo.

Skills, mods, subagents, hooks, slash commands and guides for Claude Code — installable by your agent (INSTALL.md).

Project-agnostic guides and executable agents for setting up Claude Code with 70-90% token reduction.

This library contains reusable prompts for implementing global Claude Code optimization across any project. Share with other developers or use to recreate your setup.


🤖 Install with an agent

Point your coding agent at INSTALL.md:

Read https://github.com/escapeboy/claude-code-kit/blob/master/INSTALL.md and install what fits my setup.

The agent inspects your environment, proposes a selection (starter, code intelligence, delivery, multi-agent, mods, security, unattended, stack-specific), installs it from the latest release tag after your yes, without overwriting your files, and verifies the result. llms.txt is the index agents use to find their way around.


📁 Contents

01-global-optimization

Set up global optimization (ONE-TIME, applies to ALL projects)

  • guide.md - Step-by-step installation guide
  • setup-agent.md - Executable agent for automated setup
  • checklist.md - Verification checklist
  • skills/ - Complete SKILL.md files for all 18 global skills (installed to ~/.claude/skills/)
  • optimize/ - /optimize — max token efficiency mode (multi-file: thin core + references/)
  • context/ - /ctx — memory management (multi-file: thin core + references/)
  • cache-inspector/ - /cache-inspector — cache monitoring (multi-file: thin core + references/)
  • update-docs/ - /update-docs — documentation refresh (multi-file: thin core + references/)
  • init-project/ - /init-project — new project setup (multi-file: thin core + references/)
  • agent-ready/ - /agent-ready — AI-agent-readiness audit + selective remediation (multi-file: scanner script + ROI/implementation references)
  • continuity/ - /continuity — repo-local resume→work→finalize lifecycle + evidence-weighted .continuity/STATE.md (multi-file: lint/scaffold script + format reference)
  • self-improve/ - /self-improve — closing-the-loop for the skill library: mine recurring feedback → bounded edit → tiered eval gate (deterministic skill-lint.py + trigger accuracy + LLM judge + with/without-skill behavioral eval via claude plugin eval) → converge (multi-file: linter + behavior-stats.py + deepeval_tier3.py scripts, rubric/behavior-eval/integration/deepeval-setup references)
  • video-digest/ - /video-digest — video or recording → short digest, related notes, fact-checked memory candidates
  • code-research/ - /code-research — multi-agent grounded audit of a local or git codebase into a cross-linked knowledge base (multi-file: per-phase references/)
  • agent-team/ - /agent-team — Agent Teams presets: pr-review, debug, feature, custom
  • codebase-memory/ - codebase-memory-mcp knowledge-graph queries: callers, call chains, dead code, Cypher
  • confidence-check/ - /confidence-check — ≥90% readiness gate before implementation (+ confidence.ts reference implementation)
  • decision-classify/ - /decision-classify — Mechanical / Taste / User Challenge classification to cut interruptions
  • sprint-orchestrate/ - /sprint-orchestrate — Think → Plan → Build → Review → Test → Ship → Reflect with decision gates (--from-design, --no-merge for callers like /company)
  • company/ - /company — an IT company for one task: clarify → research → split into parts → staff teams with fitting models → deliver through sprint-orchestrate; two stops for the user (multi-file: org-design, roster, briefs, workflows, memory references; back office in the company-hq mod)
  • sync-features/ - /sync-features — sync a project's feature inventory into Serena memories and auto-memory
  • ui-ux-review/ - /ui-ux-review — audit UI code for design consistency and accessibility (multi-file: examples + sample report)
  • system-prompts/ - Global system prompt files
  • global-optimization.md - Core optimization rules
  • symbol-first-protocol.md - Symbol-first exploration protocol

Time: 2-3 hours (one-time) Benefit: 70-90% token reduction on ALL future projects ROI: Pays for itself in 2-3 sessions

02-project-activation

Activate optimization for a specific project (10-15 min per project)

  • guide.md - Project activation walkthrough
  • activation-agent.md - Executable agent for Serena activation
  • memory-templates/ - Sample memory files
  • architecture-template.md - Project structure template
  • conventions-template.md - Coding patterns template

Time: 10-15 minutes per project Benefit: Project-specific memories for 60-70% session savings Required: After global setup, before starting work

03-custom-skills

Create custom slash commands (skills)

  • guide.md - How to write skills
  • skill-template.md - Blank template to copy
  • examples/ - Working examples
  • example-simple-skill.md - Simple single-action skill
  • example-complex-skill.md - Multi-action skill with integration
  • pwa.md - PWA features skill (service worker, manifest, offline, push notifications)
  • module-mcp/ - /module:mcp — Add a Laravel MCP server to any project (dual transport, domain tools, auth)
  • module-assistant/ - /module:assistant — Add an AI assistant chat panel (Livewire, PrismPHP tools, local agent support)

Use when: You want custom commands like /deploy or /migrate, or full modules like /module:mcp and /module:assistant Benefit: Encapsulate common workflows, reduce repetition; module skills bootstrap entire features

04-research-integration

Research and integrate new Claude API features

Use when: New Claude API features released, quarterly reviews Benefit: Keep documentation current, adopt new optimizations

05-token-optimization

Deep dive into token reduction techniques

Use when: Analyzing token usage, optimizing specific workflows Benefit: Understand and maximize savings, track ROI

06-advanced-patterns

Advanced techniques for complex scenarios

Use when: Complex projects, team coordination, critical decisions, cost visibility Benefit: Handle advanced scenarios with proven patterns; understand where tokens go

07-custom-commands

Custom slash commands for specialized workflows

  • debug.md - Debug Agent for systematic debugging
  • i18n.md - Internationalization management
  • qa.md - QA automation with browser testing
  • content-review.md - Content audit for accuracy, consistency, grammar, and translations
  • retro.md - Sprint retrospective with git analytics, shipping metrics, per-author breakdowns, and actionable insights

Use when: Specialized workflows, testing, debugging, sprint retrospectives, content quality assurance Benefit: Encapsulate complex workflows into simple commands

08-ui-ux-development

Production-ready UI/UX implementation with Claude Code

  • ui-ux-pro-skill.md - Complete UI/UX Pro Max skill documentation
  • 50+ UI styles (Glassmorphism, Minimalism, Brutalism, etc.)
  • 21 color palettes with accessibility guidance
  • 50 font pairings
  • shadcn/ui MCP integration
  • dashboard-workflow-guide.md - Step-by-step dashboard implementation
  • Real API data integration
  • Empty states and loading patterns
  • Security best practices (XSS prevention)
  • Dark mode and multilingual support
  • browser-testing-guide.md - Systematic browser testing
  • Chrome DevTools via Claude in Chrome MCP
  • Network, console, visual verification
  • Responsive and accessibility testing

Use when: Building dashboards, admin panels, landing pages, SaaS interfaces Benefit: 40-60% token savings, production-ready code with security and accessibility Time: 60-90 minutes per dashboard (vs 3-4 hours manual)

09-laravel-mcp-integration

Connect Claude Code with Laravel's MCP ecosystem

Use when: Working on Laravel 11.x/12.x projects with Claude Code Benefit: Project-aware assistance via Laravel Boost + package discovery via LaraPlugins.io Setup: 5 minutes per project (composer install + MCP registration)

10-subagents

Create custom AI agents with specialized knowledge and tools

  • README.md - Subagent system overview
  • guide.md - Complete subagent creation guide + all v2.1.83 frontmatter fields + production agents
  • plan-challenger (Opus) — adversarial plan review across 5 dimensions with refutation check
  • output-evaluator (Haiku) — LLM-as-Judge: APPROVE/NEEDS_REVIEW/REJECT before commit
  • loop-monitor (Haiku) — watchdog for autonomous sessions: stall/runaway/loop detection
  • examples/ - Working subagent examples
  • code-reviewer.md - Read-only code review agent
  • laravel-specialist.md - Laravel development agent
  • debugger.md - Debugging specialist
  • test-generator.md - Test generation agent

Use when: Repetitive specialized tasks, team standardization, cost optimization Benefit: Reusable agents with controlled tool access and model selection Setup: 5-10 minutes per agent definition

11-mobile-development

Mobile development with Claude Code across all major platforms

Use when: Developing iOS (Swift/SwiftUI), Android (Kotlin/Compose), React Native, or Flutter apps Benefit: Platform-specific MCP integration, build/test automation, device control Setup: 5-10 minutes per platform (MCP installation + CLAUDE.md template)

12-desktop-development

Desktop development with Claude Code for macOS, Tauri, and Electron

Use when: Building macOS native (SwiftUI/AppKit), Tauri (Rust + Web), or Electron (Node.js + Chromium) desktop apps Benefit: Platform-specific MCP integration, build/package automation, code signing and notarization workflows Setup: 5-10 minutes per platform (MCP installation + CLAUDE.md template)

14-webmcp

WebMCP — structured browser tools for AI agents (W3C Draft, Chrome 146 Canary)

  • guide.md - WebMCP integration guide
  • What WebMCP solves (89% token savings vs screenshot-based approaches)
  • WebMCP vs MCP comparison (frontend vs backend)
  • navigator.modelContext API reference with code examples
  • Implementation patterns (read-only, form actions, declarative HTML)
  • Integration with Chrome MCP and Playwright MCP
  • CLAUDE.md template for WebMCP-enabled projects
  • Current limitations and browser support matrix

Use when: Building web applications that AI agents will interact with Benefit: Structured tool access instead of DOM scraping; 89% token reduction Status: Early Preview — Chrome 146 Canary only, spec actively changing


13-security-hardening

Protect Claude Code workflows from MCP attacks, prompt injection, and accidental data loss

  • guide.md - Complete security hardening guide
  • MCP vetting checklist + community-vetted safe list
  • Known CVEs (2025-2026) with versions and mitigations
  • Prompt injection defense hooks (PreToolUse + PostToolUse)
  • 6 production safety rules with settings.json + hook implementations
  • permissions.deny hardening templates (global + project-level)
  • Agent Skills supply chain risks and scanning
  • hooks/ - Production hook library (actual scripts, copy-paste ready)
  • dangerous-actions-blocker.py — blocks rm -rf /-class commands in any spelling, force-push to main, DROP TABLE, over-broad pkill/killall, edits to key files
  • pre-commit-secrets.py — scans staged content for API keys / private keys / DB URLs before every git commit
  • block-interactive-sudo.py — refuses sudo that would hang on a password prompt
  • tests/ — two-sided matrices (must-block AND must-pass) · WHY.md — the failure behind each hook
  • README with settings.json wiring and the PreToolUse hook contract
  • Productivity hooks (package-version checker, session-start memory loader, shell-habits) live in 01-global-optimization/hooks/

Use when: Team environments, production codebases, regulated industries, before adding new MCP servers Benefit: Prevent data exfiltration, block destructive operations, audit MCP supply chain Time: 15-30 minutes for initial hardening; 5 minutes per new MCP added

16-autonomous-agents

Run Claude Code unattended — cron agents, heartbeat watchdogs, and session journaling

  • guide.md - Autonomous & scheduled agents guide
  • The three primitives: headless cron runs, /loop, and hooks — and when each applies
  • Daily journaling agent recipe (~120 production runs/month): idempotent in-place note editing, replace-vs-append sections, self-contained cron briefs
  • Heartbeat watchdog protocol: exact HEARTBEAT_OK token, 200-token failure budget, probe allowlist — born from sessions killed for drifting into investigations
  • Watchdog patterns: stall / token-runaway / repeated-action-loop detection
  • Anti-pattern table — each entry cost a real incident
  • heartbeat-template.md - Copy-paste HEARTBEAT protocol file
  • session-summary-hook.py - Stop hook: Haiku-summarized session entries appended to a daily note (~$0.001/session)

Use when: Scheduled health checks, automated journaling, any unattended Claude Code run Benefit: Agents that complete within budget instead of drifting; a daily work journal nobody has to write Time: 30-60 minutes for the first cron agent

17-mods

Claude Code mods (v2.1.287+) — TypeScript hooks inside the engine

  • guide.md - What mods can do that settings hooks cannot, anatomy, events and engine API, patterns that held up, testing
  • marketplace/ - Example marketplace ai-prompts-mods: 13 mods with tests — context-meter, cache-guard, spend-ledger, subagent-models, secret-redactor, ssh-guard, deploy-verify, ci-watch, cleanup-tracker, aside, fleet-status, lang-guard, company-hq

Use when: A policy must hold on every tool call or subagent spawn, output must be rewritten before the model sees it, or you want live UI (meters, panes, status) Benefit: Secrets out of transcripts, model routing that plugin updates cannot undo, cache and spend visible while you work Time: 10 minutes to install the set; 1-2 hours to write your first mod


🚀 Quick Start

First Time Setup (2-3 hours)

Option 1: Automated (Recommended)

# Navigate to Claude Code
cd ~/.claude

# Use the setup agent
# Copy contents of 01-global-optimization/setup-agent.md
# Paste into Claude Code conversation
# Agent will create all files automatically

Option 2: Manual

# Follow the step-by-step guide
# Read: 01-global-optimization/guide.md
# Create files as instructed
# Verify with: 01-global-optimization/checklist.md

Activate for Your Project (10-15 min)

# Navigate to your project
cd ~/projects/your-project

# Use the activation agent
# Copy contents of 02-project-activation/activation-agent.md
# Paste into Claude Code conversation
# Agent will activate Serena and create memories

Start Optimized Work

# In your project directory
/optimize "Your task here"

# Or use /init-project for new projects
/init-project --full

📊 Expected Outcomes

Token Reduction Targets

ScenarioBaselineOptimizedSavings
Simple task (bug fix)22,000 tokens1,600 tokens93%
Medium task (new feature)31,000 tokens8,500 tokens73%
Complex task (module creation)85,000 tokens18,000 tokens79%

Conservative target: 30-50% overall reduction Aggressive target: 50-70% with full optimization Maximum achieved: 80-90% with prompt caching on large contexts

Cost Savings

Per session (average medium task):

  • Baseline: $0.93 (31,000 tokens @ $3/M)
  • Optimized: $0.26 (8,500 tokens @ $3/M)
  • Savings: $0.67 per session (72%)

Monthly (30 sessions):

  • Baseline: $27.90
  • Optimized: $7.80
  • Savings: $20.10 per month

Annual (360 sessions):

  • Baseline: $334.80
  • Optimized: $93.60
  • Savings: $241.20 per year

Multiple projects (3 projects, 60 sessions/month):

  • Annual savings: $723.60

🛠️ What Gets Created

Global Files (in ~/.claude/)

Agents (orchestration):

  • agents/pm-orchestrator.md - Central coordinator
  • agents/plan-challenger.md - Adversarial plan review (Opus)
  • agents/output-evaluator.md - Code quality judge before commit (Haiku)
  • agents/loop-monitor.md - Autonomous session watchdog (Haiku)

Hooks (automation):

  • hooks/dangerous-actions-blocker.py - Blocks destructive commands and protected files
  • hooks/pre-commit-secrets.py - Scans staged files for API keys before commit
  • `hooks/block-interactive-sudo.p
Source 2 files
hooks/register.tsx 115 lines
1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { Meter } from '../types'
5
6const meter = atom({ plugin: 'context-meter', key: 'meter' } as const, null)
7// The highest threshold already announced this session, so each fires once.
8const warned = atom({ plugin: 'context-meter', key: 'warned' } as const, 0)
9const isHidden = atom({ plugin: 'context-meter', key: 'isHidden' } as const, false)
10
11// Long sessions pay cache-read on the whole context every turn (one real
12// session reached 930K). Past these points a fresh session is cheaper.
13const THRESHOLDS = [50, 70] as const
14
15export const kTokens = (n: number) => (n >= 1_000_000 ? `${(n / 1_000_000).toFixed(2)}M` : `${Math.round(n / 1000)}K`)
16
17export const formatMeter = (m: Meter): string => {
18  const parts = [
19    m.tokens === undefined ? `ctx –/${kTokens(m.window)}` : `ctx ${kTokens(m.tokens)}/${kTokens(m.window)} ${m.percent ?? 0}%`,
20    `cache read ${kTokens(m.cacheRead)} · write ${kTokens(m.cacheWrite)}`,
21  ]
22  if (m.usd !== undefined) parts.push(`$${m.usd.toFixed(2)}`)
23  for (const l of m.limits) parts.push(`${l.kind === 'five_hour' ? '5h' : l.kind === 'seven_day' ? '7d' : l.kind} ${Math.round(l.percentUsed)}%`)
24  return parts.join(' · ')
25}
26
27export const crossed = (percent: number | undefined, already: number): number | undefined => {
28  if (percent === undefined) return undefined
29  const top = THRESHOLDS.filter(t => percent >= t && t > already).pop()
30  return top
31}
32
33// Rule "one session = one task": past 70% the band offers a handoff. It only
34// prepares the next session; it never runs /clear (the user's choice, 08.10).
35export const HANDOFF_PROMPT = [
36  'Prepare a handoff so this work can continue in a fresh session. Do not run /clear.',
37  '1. If the working directory has .continuity/, run the continuity skill\'s finalize (update STATE.md with evidence tags, then lint).',
38  '2. Otherwise write ~/.claude/handoffs/<project>-<YYYY-MM-DD>.md: goal, what is done (verified), what is in flight, what failed and why, next steps, key files.',
39  '3. End with the exact first message to paste into the new session, and nothing else after it.',
40].join('\n')
41
42export const register: Register = on => {
43  on('session.start', async ($, e, next) => {
44    await $.command.register({ name: 'meter', description: 'Show or hide the context meter band', immediate: true })
45    await $.command.register({ name: 'handoff', description: 'Finalize this session into a handoff for a fresh one (no /clear)' })
46    return next(e)
47  })
48
49  on('command.run', { command: 'handoff' }, async $ => {
50    await $.prompt.submit({ text: HANDOFF_PROMPT })
51    return { text: 'Handoff requested.' }
52  })
53
54  on('command.run', { command: 'meter' }, async $ => {
55    const hidden = await update($, isHidden, h => !h)
56    const m = await read($, meter)
57    return { text: `${hidden ? 'Meter hidden.' : 'Meter shown.'}${m ? ' ' + formatMeter(m) : ''}` }
58  })
59
60  // Main-loop requests only: a subagent's request says nothing about this window.
61  on('turn.step', async function* ($, e, next) {
62    const result = yield* next(e)
63    if (e.agentId === undefined && result.usage) {
64      const usage = await $.session.usage()
65      const m: Meter = {
66        tokens: usage.context.tokens,
67        window: usage.context.window,
68        percent: usage.context.percent,
69        cacheRead: result.usage.cache_read_input_tokens ?? 0,
70        cacheWrite: result.usage.cache_creation_input_tokens ?? 0,
71        usd: usage.cost?.usd,
72        limits: usage.rateLimits.map(l => ({ kind: l.kind, percentUsed: l.percentUsed })),
73      }
74      await update($, meter, () => m)
75
76      const hit = crossed(m.percent, await read($, warned))
77      if (hit !== undefined) {
78        await update($, warned, () => hit)
79        $.ui.toast(`Context at ${m.percent}%: ${hit >= 70 ? '/handoff, then a fresh session' : 'finish this task, then a fresh session'} (cache read grows every turn).`)
80      }
81    }
82    return result
83  })
84
85  // /clear starts the window over.
86  on('session.end', async ($, e, next) => {
87    if (e.reason === 'clear') {
88      await update($, meter, () => null)
89      await update($, warned, () => 0)
90    }
91    return next(e)
92  })
93
94  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
95    const m = await read($, meter)
96    if (e.props.hasSurvey || m === null || (await read($, isHidden))) return next(e)
97
98    const { Box, Button, Text } = $.ui.resolve(e)
99    const percent = m.percent ?? 0
100    const color = percent >= 70 ? 'red' : percent >= 50 ? 'yellow' : undefined
101
102    return (
103      <Box>
104        <Text color={color} dimColor={color === undefined} wrap="truncate-end">
105          {formatMeter(m)}{' '}
106        </Text>
107        {percent >= 70 ? (
108          <Button key="handoff" label="Handoff" variant="primary" onPress={() => $.prompt.submit({ text: HANDOFF_PROMPT })} />
109        ) : null}
110        <Button key="hide" label="Hide" plain onPress={() => update($, isHidden, () => true)} />
111      </Box>
112    )
113  })
114}
115
types/index.d.ts 16 lines
1export type Meter = {
2  tokens?: number
3  window: number
4  percent?: number
5  cacheRead: number
6  cacheWrite: number
7  usd?: number
8  limits: { kind: string; percentUsed: number }[]
9}
10
11declare module 'claude-code' {
12  interface PluginState {
13    'context-meter': { meter: Meter | null; warned: number; isHidden: boolean }
14  }
15}
16