Pins subagent models to a model-routing policy (Opus for judgement, Haiku for mechanical work, Sonnet otherwise) and logs every spawn.

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.
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.
Set up global optimization (ONE-TIME, applies to ALL projects)
~/.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 candidatescode-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, customcodebase-memory/ - codebase-memory-mcp knowledge-graph queries: callers, call chains, dead code, Cypherconfidence-check/ - /confidence-check — ≥90% readiness gate before implementation (+ confidence.ts reference implementation)decision-classify/ - /decision-classify — Mechanical / Taste / User Challenge classification to cut interruptionssprint-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-memoryui-ux-review/ - /ui-ux-review — audit UI code for design consistency and accessibility (multi-file: examples + sample report)global-optimization.md - Core optimization rulessymbol-first-protocol.md - Symbol-first exploration protocolTime: 2-3 hours (one-time) Benefit: 70-90% token reduction on ALL future projects ROI: Pays for itself in 2-3 sessions
Activate optimization for a specific project (10-15 min per project)
architecture-template.md - Project structure templateconventions-template.md - Coding patterns templateTime: 10-15 minutes per project Benefit: Project-specific memories for 60-70% session savings Required: After global setup, before starting work
Create custom slash commands (skills)
example-simple-skill.md - Simple single-action skillexample-complex-skill.md - Multi-action skill with integrationpwa.md - PWA features skill (service worker, manifest, offline, push notifications)/module:mcp — Add a Laravel MCP server to any project (dual transport, domain tools, auth)/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
Research and integrate new Claude API features
Use when: New Claude API features released, quarterly reviews Benefit: Keep documentation current, adopt new optimizations
Deep dive into token reduction techniques
Use when: Analyzing token usage, optimizing specific workflows Benefit: Understand and maximize savings, track ROI
Advanced techniques for complex scenarios
/agent-team skill with pr-review, debug, feature, custom presetsUse when: Complex projects, team coordination, critical decisions, cost visibility Benefit: Handle advanced scenarios with proven patterns; understand where tokens go
Custom slash commands for specialized workflows
Use when: Specialized workflows, testing, debugging, sprint retrospectives, content quality assurance Benefit: Encapsulate complex workflows into simple commands
Production-ready UI/UX implementation with Claude Code
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)
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)
Create custom AI agents with specialized knowledge and tools
plan-challenger (Opus) — adversarial plan review across 5 dimensions with refutation checkoutput-evaluator (Haiku) — LLM-as-Judge: APPROVE/NEEDS_REVIEW/REJECT before commitloop-monitor (Haiku) — watchdog for autonomous sessions: stall/runaway/loop detectioncode-reviewer.md - Read-only code review agentlaravel-specialist.md - Laravel development agentdebugger.md - Debugging specialisttest-generator.md - Test generation agentUse 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
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)
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)
WebMCP — structured browser tools for AI agents (W3C Draft, Chrome 146 Canary)
navigator.modelContext API reference with code examplesUse 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
Protect Claude Code workflows from MCP attacks, prompt injection, and accidental data loss
settings.json + hook implementationspermissions.deny hardening templates (global + project-level)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 filespre-commit-secrets.py — scans staged content for API keys / private keys / DB URLs before every git commitblock-interactive-sudo.py — refuses sudo that would hang on a password prompttests/ — two-sided matrices (must-block AND must-pass) · WHY.md — the failure behind each hooksettings.json wiring and the PreToolUse hook contractUse 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
Run Claude Code unattended — cron agents, heartbeat watchdogs, and session journaling
/loop, and hooks — and when each appliesHEARTBEAT_OK token, 200-token failure budget, probe allowlist — born from sessions killed for drifting into investigationsUse 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
Claude Code mods (v2.1.287+) — TypeScript hooks inside the engine
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-hqUse 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
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
# 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
# In your project directory
/optimize "Your task here"
# Or use /init-project for new projects
/init-project --full
| Scenario | Baseline | Optimized | Savings |
|---|---|---|---|
| Simple task (bug fix) | 22,000 tokens | 1,600 tokens | 93% |
| Medium task (new feature) | 31,000 tokens | 8,500 tokens | 73% |
| Complex task (module creation) | 85,000 tokens | 18,000 tokens | 79% |
Conservative target: 30-50% overall reduction Aggressive target: 50-70% with full optimization Maximum achieved: 80-90% with prompt caching on large contexts
Per session (average medium task):
Monthly (30 sessions):
Annual (360 sessions):
Multiple projects (3 projects, 60 sessions/month):
~/.claude/)Agents (orchestration):
agents/pm-orchestrator.md - Central coordinatoragents/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 fileshooks/pre-commit-secrets.py - Scans staged files for API keys before commithooks/register.ts 79 lines1import type { Register } from 'claude-code'
2
3// Model routing policy: Opus only for judgement-heavy agents, Haiku for
4// mechanical ones, Sonnet for the rest. Agent frontmatter says the same, but a
5// plugin update can overwrite it; this table keeps the policy in force anyway.
6const POLICY: Record<string, string> = {
7 'adversarial-verifier': 'opus',
8 'plan-challenger': 'opus',
9 'security-engineer': 'opus',
10 'system-architect': 'opus',
11 'business-panel-experts': 'opus',
12 'icon-manager': 'haiku',
13 'loop-monitor': 'haiku',
14 'output-evaluator': 'haiku',
15 'repo-index': 'haiku',
16 'requirements-analyst': 'haiku',
17 'technical-writer': 'haiku',
18 // Built-in catch-alls inherit the parent's model otherwise, which is Opus
19 // whenever the main session runs on Opus.
20 'general-purpose': 'sonnet',
21 claude: 'sonnet',
22}
23
24const LOG_KEY = 'spawns'
25const LOG_MAX = 500
26
27export type SpawnRecord = {
28 at: number
29 type: string
30 asked?: string
31 set?: string
32 ran?: string
33 cwd: string
34}
35
36export const policyModel = (subagentType: string, asked: string | undefined): string | undefined =>
37 asked === undefined ? POLICY[subagentType] : undefined
38
39export const register: Register = on => {
40 on('session.start', async ($, e, next) => {
41 await $.command.register({
42 name: 'agent-models',
43 description: 'Show the last subagent spawns and the model each ran on',
44 argumentHint: '[count]',
45 })
46 return next(e)
47 })
48
49 on('agent.spawn', async ($, e, next) => {
50 // An explicit `model` from the caller wins; forks always inherit.
51 const set = e.fork ? undefined : policyModel(e.subagentType, e.model)
52 const result = await next(set ? { ...e, model: set } : e)
53
54 const log = ((await $.store.get(LOG_KEY)) as SpawnRecord[] | undefined) ?? []
55 log.push({
56 at: await $.clock.now(),
57 type: e.subagentType,
58 asked: e.model,
59 set,
60 ran: result.deny === undefined ? result.model : undefined,
61 cwd: await $.session.cwd(),
62 })
63 await $.store.set(LOG_KEY, log.slice(-LOG_MAX))
64 return result
65 }).catch(($, e, next) => next(e)) // a failure here must never stop a subagent
66
67 on('command.run', { command: 'agent-models' }, async ($, e) => {
68 const count = Number(e.args) || 20
69 const log = ((await $.store.get(LOG_KEY)) as SpawnRecord[] | undefined) ?? []
70 if (log.length === 0) return { text: 'No subagent spawns recorded yet.' }
71 const lines = log.slice(-count).map(r => {
72 const when = new Date(r.at).toISOString().slice(5, 16).replace('T', ' ')
73 const how = r.set ? `policy → ${r.set}` : r.asked ? `asked ${r.asked}` : 'own/inherit'
74 return `${when} ${r.type.padEnd(28)} ${(r.ran ?? 'denied').padEnd(22)} ${how}`
75 })
76 return { text: `Last ${lines.length} of ${log.length} spawns:\n${lines.join('\n')}` }
77 })
78}
79