### Development Setup Commands Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/CONTRIBUTING.md Commands to clone the repository, install dependencies, and run tests for local development. ```bash git clone https://github.com/YOUR_USERNAME/claude-code-prompt-optimizer.git cd claude-code-prompt-optimizer npm install npm test ``` -------------------------------- ### Step-by-Step Install - Install Dependencies Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Install the required Node.js packages for the project using npm. Verify the installation by listing installed packages. ```bash # Install required packages npm install # Verify installation npm list @anthropic-ai/claude-agent-sdk tsx ``` -------------------------------- ### Step-by-Step Install - Clone Repository Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Clone the project repository and navigate into the directory. This is the first step for manual installation. ```bash # Navigate to your preferred directory cd ~/projects # or wherever you keep your code # Clone the repository git clone https://github.com/johnpsasser/claude-code-prompt-optimizer.git # Enter the project directory cd claude-code-prompt-optimizer ``` -------------------------------- ### Install Dependencies Manually Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/README.md Manually install project dependencies by cloning the repository, changing into the directory, and running 'npm install'. This is part of the manual setup process. ```bash git clone https://github.com/johnpsasser/claude-code-prompt-optimizer.git cd claude-code-prompt-optimizer npm install ``` -------------------------------- ### Custom Installation Path Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Install the optimizer to a custom system-wide location and update the command path in settings.json. ```bash # System-wide installation sudo cp -r claude-code-prompt-optimizer /opt/ sudo chmod 755 /opt/claude-code-prompt-optimizer/src/hooks/optimize-prompt.sh ``` ```json # Update settings.json to: "command": "/opt/claude-code-prompt-optimizer/src/hooks/optimize-prompt.sh" ``` -------------------------------- ### Step-by-Step Install - Run Test Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Run the npm test command to execute the optimizer with the test input. This verifies the installation and hook configuration. ```bash npm test ``` -------------------------------- ### Step-by-Step Install - Get Hook Path Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Get the absolute path to the optimize-prompt.sh script from within the project directory. This path is needed for the hook configuration. ```bash # From within the project directory echo "$PWD/src/hooks/optimize-prompt.sh" ``` -------------------------------- ### Step-by-Step Install - Test Input Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Create a test input JSON file to simulate a prompt submission for testing the optimizer hook. ```bash cat > test-input.json << 'EOF' { "prompt": " write a hello world function", "session_id": "test-session", "transcript_path": "/tmp/test", "hook_event_name": "UserPromptSubmit" } EOF ``` -------------------------------- ### Step-by-Step Install - Verify CLI and Auth Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Verify that the Claude CLI is installed and that you are logged in. This is part of the stored OAuth configuration. ```bash # Check CLI is installed claude --version # Start Claude to verify auth (exit with Ctrl+C) claude ``` -------------------------------- ### Automated Installer for Claude Code Prompt Optimizer Source: https://context7.com/johnpsasser/claude-code-prompt-optimizer/llms.txt Clone the repository and run the automated installer script to set up the hook. This script checks prerequisites, installs dependencies, configures authentication, registers the hook, and performs a verification test. ```bash git clone https://github.com/johnpsasser/claude-code-prompt-optimizer.git cd claude-code-prompt-optimizer npm run install-hook ``` ```text ======================================== Claude Code Prompt Optimizer Installer ======================================== [OK] Node.js 22.x.x [OK] Claude CLI found: 1.x.x [installer] Installing dependencies... [OK] Dependencies installed --- Authentication Setup --- Choose your auth method: 1) Stored OAuth (already logged in via `claude login`) [recommended] 2) OAuth token (Claude Pro / MAX subscribers) 3) API key (Anthropic API credits) [OK] Hook added to /home/user/.claude/settings.json [OK] chmod +x /path/to/src/hooks/optimize-prompt.sh [OK] Verification passed — hook returns valid output ======================================== Installation complete! ======================================== Usage: add to any prompt in Claude Code ``` -------------------------------- ### Automated Hook Installation Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/README.md Run the npm script to automate the installation of the hook. ```bash npm run install-hook ``` -------------------------------- ### Step-by-Step Install - Make Hook Executable Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Ensure the optimize-prompt.sh script has execute permissions. This is necessary for the hook to run correctly. ```bash # Ensure the shell script has execute permissions chmod +x src/hooks/optimize-prompt.sh ``` -------------------------------- ### Install Claude Code Prompt Optimizer Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/README.md Use this command to clone the repository, navigate into the directory, and run the installer script for dependencies, authentication, and hook configuration. ```bash git clone https://github.com/johnpsasser/claude-code-prompt-optimizer.git cd claude-code-prompt-optimizer npm run install-hook ``` -------------------------------- ### Example: Optimize REST API Creation Prompt Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/README.md Demonstrates the input prompt format for optimizing a request to create a REST API. The optimizer will expand this into detailed specifications. ```bash create a REST API ``` -------------------------------- ### In-Session Usage Patterns for Tag Source: https://context7.com/johnpsasser/claude-code-prompt-optimizer/llms.txt Demonstrates various ways to use the `` tag within Claude Code prompts to guide the AI. Examples cover minimal usage, preserving identifiers, combining requirements, and specific workflows like debugging and refactoring. ```shell # Minimal usage — vague prompt expanded into structured spec create a REST API # Preserve exact identifiers with double quotes (skip-comment rule) implement a function called "calculateTotalPrice" that validates input # Combine multiple requirements in a single prompt build a real-time chat application with WebSockets, auth, and message persistence # Debugging workflow fix the authentication bug in the OAuth flow # Refactoring workflow refactor the user service for better performance and testability # Architecture planning design a microservices migration strategy for the monolith ``` -------------------------------- ### Install Node.js Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Install Node.js version 18 or later if you encounter 'npx: command not found' errors. Instructions provided for macOS and Ubuntu/Debian. ```bash # macOS: brew install node ``` ```bash # Ubuntu/Debian: curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - sudo apt-get install -y nodejs ``` -------------------------------- ### Example Optimization Prompt Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Use the `` tag to trigger prompt optimization. Enclose specific text in quotes to preserve exact wording. ```plaintext build a real-time chat application ``` -------------------------------- ### Step-by-Step Install - Set OAuth Token (Session) Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Temporarily set the CLAUDE_CODE_OAUTH_TOKEN environment variable for the current terminal session. This is for Claude Pro/MAX subscribers. ```bash export CLAUDE_CODE_OAUTH_TOKEN="your-oauth-token" ``` -------------------------------- ### Example: Optimize Code Refactoring Prompt Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/README.md Shows the input prompt for optimizing a request to refactor code for better performance. The output will be a structured plan for profiling and refactoring. ```bash refactor this codebase for better performance ``` -------------------------------- ### Step-by-Step Install - Configure Hook Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Add the prompt optimizer hook configuration to your Claude Code settings.json file. Ensure you replace the placeholder path with your actual file path. ```json { "hooks": { "UserPromptSubmit": [ { "hooks": [ { "type": "command", "command": "/absolute/path/to/claude-code-prompt-optimizer/src/hooks/optimize-prompt.sh" } ] } ] } } ``` -------------------------------- ### Step-by-Step Install - Set API Key (Permanent bash) Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Permanently set the ANTHROPIC_API_KEY environment variable by adding it to your bash profile. Remember to source the file to apply changes. ```bash echo 'export ANTHROPIC_API_KEY="sk-ant-api03-..."' >> ~/.bashrc source ~/.bashrc ``` -------------------------------- ### Update Optimizer Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Update the optimizer by pulling the latest changes from the main branch and installing dependencies. ```bash cd claude-code-prompt-optimizer git pull origin main npm install ``` -------------------------------- ### Step-by-Step Install - Set OAuth Token (Permanent bash) Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Permanently set the CLAUDE_CODE_OAUTH_TOKEN environment variable by adding it to your bash profile. Remember to source the file to apply changes. ```bash echo 'export CLAUDE_CODE_OAUTH_TOKEN="your-oauth-token"' >> ~/.bashrc source ~/.bashrc ``` -------------------------------- ### Step-by-Step Install - Set API Key (Permanent zsh) Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Permanently set the ANTHROPIC_API_KEY environment variable by adding it to your zsh profile. Remember to source the file to apply changes. ```bash echo 'export ANTHROPIC_API_KEY="sk-ant-api03-..."' >> ~/.zshrc source ~/.zshrc ``` -------------------------------- ### Step-by-Step Install - Set OAuth Token (Permanent zsh) Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Permanently set the CLAUDE_CODE_OAUTH_TOKEN environment variable by adding it to your zsh profile. Remember to source the file to apply changes. ```bash echo 'export CLAUDE_CODE_OAUTH_TOKEN="your-oauth-token"' >> ~/.zshrc source ~/.zshrc ``` -------------------------------- ### Get Absolute Path and Make Executable Source: https://context7.com/johnpsasser/claude-code-prompt-optimizer/llms.txt Determine the absolute path to the hook script and set execute permissions for it. This is necessary for manual hook registration. ```bash cd claude-code-prompt-optimizer ``` ```bash echo "$PWD/src/hooks/optimize-prompt.sh" ``` ```bash chmod +x src/hooks/optimize-prompt.sh ``` -------------------------------- ### Set Up CLAUDE_CODE_OAUTH_TOKEN Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/README.md Obtain your OAuth token using the 'claude auth token' command and then export it as an environment variable in your shell profile. This method is preferred for Claude Pro/MAX subscribers. ```bash # Get your token claude auth token # Add to shell profile export CLAUDE_CODE_OAUTH_TOKEN="your-oauth-token" ``` -------------------------------- ### Optimize Feature Implementation Request Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/examples/example-prompts.md Use this prompt to generate a framework for implementing a new feature, such as dark mode. It covers design system adaptation, technical implementation, and UI considerations. ```plaintext add dark mode to the app ``` -------------------------------- ### Run Optimize Prompt Script with Debug Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/README.md Execute the prompt optimization script with debug output enabled. Input is piped from a JSON file. ```bash DEBUG=true bash src/hooks/optimize-prompt.sh < examples/test-input.json ``` -------------------------------- ### Configure Authentication for Agent SDK Source: https://context7.com/johnpsasser/claude-code-prompt-optimizer/llms.txt Set up authentication for the Agent SDK. The SDK prioritizes CLAUDE_CODE_OAUTH_TOKEN, then ANTHROPIC_API_KEY, and finally stored OAuth from 'claude login'. ```bash # Option 1: Stored OAuth — no env vars needed if already logged in claude login # one-time setup ``` ```bash # Option 2: OAuth token (Claude Pro / MAX subscribers) claude auth token # retrieve token export CLAUDE_CODE_OAUTH_TOKEN="your-token-here" ``` ```bash # Persist to shell profile (zsh) echo 'export CLAUDE_CODE_OAUTH_TOKEN="your-token-here"' >> ~/.zshrc source ~/.zshrc ``` ```bash # Option 3: API key export ANTHROPIC_API_KEY="sk-ant-api03-..." ``` ```bash # Persist to shell profile (bash) echo 'export ANTHROPIC_API_KEY="sk-ant-api03-..."' >> ~/.bashrc source ~/.bashrc ``` ```bash # Verify which credentials are active echo "OAuth token: ${CLAUDE_CODE_OAUTH_TOKEN:+set}" echo "API key: ${ANTHROPIC_API_KEY:+set}" ``` -------------------------------- ### Testing the Prompt Optimizer Hook Source: https://context7.com/johnpsasser/claude-code-prompt-optimizer/llms.txt Provides commands for testing the prompt optimizer hook locally. Includes running against a test fixture, streaming debug output, and an inline one-liner test using Node.js. ```bash # Run against the bundled test fixture (no Claude Code session needed) npm test # Equivalent to: npx tsx src/hooks/optimize-prompt.ts < examples/test-input.json # Run with debug output streamed to stderr npm run test:debug # Equivalent to: DEBUG=true bash src/hooks/optimize-prompt.sh < examples/test-input.json # Inline one-liner test node -e " const input = { prompt: ' create a REST API', session_id: 'test', transcript_path: '/tmp/test', hook_event_name: 'UserPromptSubmit' }; console.log(JSON.stringify(input)); " | npx tsx src/hooks/optimize-prompt.ts # Expected stderr output: # ------------------------------------------------------------ # PROMPT OPTIMIZER - ULTRATHINK MODE ENABLED # ------------------------------------------------------------ # # Original Prompt: # create a REST API # # Optimized Prompt: # Design and implement a production-ready RESTful API... # ------------------------------------------------------------ ``` -------------------------------- ### Optimize Prompt using Agent SDK `query` Source: https://context7.com/johnpsasser/claude-code-prompt-optimizer/llms.txt Calls the Claude Agent SDK's `query` function to optimize a given prompt. It uses a clean environment and a specialist system prompt for single-turn optimization. Ensure `buildCleanEnv()` is available to handle environment variables correctly. ```typescript import { query } from '@anthropic-ai/claude-agent-sdk'; // Simplified illustration of the core call async function optimizePrompt(originalPrompt: string): Promise { const env = buildCleanEnv(); // strips CLAUDECODE + ANTHROPIC_API_KEY for subprocess const q = query({ prompt: `Original prompt to optimize:\n${originalPrompt}`, options: { model: 'claude-sonnet-4-5-20250929', systemPrompt: OPTIMIZATION_SYSTEM_PROMPT, maxTurns: 1, // single-turn — no tool calls needed allowedTools: [], permissionMode: 'bypassPermissions', settingSources: [], env, }, }); let result = ''; for await (const msg of q) { if (msg.type === 'result' && msg.subtype === 'success') { result = msg.result; } } return result.trim() || originalPrompt; // fallback to original on empty result } ``` ```typescript // Usage const optimized = await optimizePrompt("fix the login bug"); // → "You are tasked with systematically debugging and resolving a login // functionality issue. Execute this task using a structured diagnostic // and remediation framework.\n\n## Primary Objective\n..." ``` -------------------------------- ### Run Optimize Prompt Script Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/README.md Execute the prompt optimization script directly using npx and tsx. Input is piped from a JSON file. ```bash npx tsx src/hooks/optimize-prompt.ts < examples/test-input.json ``` -------------------------------- ### Set Up ANTHROPIC_API_KEY Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/README.md Export your Anthropic API key as an environment variable in your shell profile. This is used for API credit users when CLAUDE_CODE_OAUTH_TOKEN is not set. ```bash export ANTHROPIC_API_KEY="sk-ant-api03-..." ``` -------------------------------- ### Optimize Database Performance Prompt Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/examples/example-prompts.md Use the tag to transform a simple request into a detailed database optimization strategy. This includes phases for auditing, implementation, and monitoring. ```plaintext optimize database performance ``` ```plaintext Execute a comprehensive database optimization strategy to improve query performance and system scalability. ## Optimization Framework ### Phase 1: Performance Audit 1. **Current State Analysis** - Query execution plans - Slow query log analysis - Index usage statistics - Table size and growth patterns - Connection pool metrics 2. **Bottleneck Identification** - N+1 query problems - Missing indexes - Table scan operations - Lock contention issues - Memory usage patterns ### Phase 2: Optimization Implementation 1. **Index Strategy** - Create missing indexes - Remove redundant indexes - Composite index optimization - Covering index implementation 2. **Query Optimization** - Rewrite inefficient queries - Implement query caching - Batch operation strategies - Pagination optimization 3. **Schema Improvements** - Denormalization where appropriate - Partitioning strategies - Archive old data - Data type optimization ### Phase 3: Monitoring & Maintenance - Performance baseline establishment - Automated monitoring setup - Alert configuration - Regular maintenance schedule ``` -------------------------------- ### Using Optimizer - Add Optimize Tag Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md To use the prompt optimizer in Claude Code, simply prepend your prompt with the `` tag. The optimizer will then enhance your prompt before execution. ```text create a user authentication system ``` -------------------------------- ### Enable Debug Mode Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Enable debug logging by setting the DEBUG environment variable. Check debug logs in the specified file. ```bash # In your shell profile export DEBUG=true ``` ```bash # Check debug logs tail -f /tmp/claude-code-hook-debug.log ``` -------------------------------- ### Make Hook Executable Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/README.md Grant execute permissions to the optimize-prompt.sh script using chmod. This is a necessary step for the hook to function correctly. ```bash chmod +x src/hooks/optimize-prompt.sh ``` -------------------------------- ### Resolve Hook Path Issues Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md If the hook path is not found, navigate to the project directory and print the absolute path to the hook script. Copy this path to settings.json. ```bash # Get absolute path from project directory cd claude-code-prompt-optimizer echo "$PWD/src/hooks/optimize-prompt.sh" ``` -------------------------------- ### Combine Multiple Requirements Prompt Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/examples/example-prompts.md The optimizer can handle complex requests by combining multiple requirements, such as building a REST API with authentication, rate limiting, and WebSocket support. ```plaintext build a REST API with authentication, rate limiting, and WebSocket support ``` -------------------------------- ### Configure Claude Code Hook Settings Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/README.md Add this JSON configuration to your '~/.claude/settings.json' file to register the optimize-prompt.sh hook for UserPromptSubmit events. ```json { "hooks": { "UserPromptSubmit": [ { "hooks": [ { "type": "command", "command": "/path/to/claude-code-prompt-optimizer/src/hooks/optimize-prompt.sh" } ] } ] } } ``` -------------------------------- ### Iterative Refinement Prompt Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/examples/example-prompts.md You can use the tag iteratively, applying it to already detailed requirements for further refinement and structure. ```plaintext [your detailed requirements here] ``` -------------------------------- ### Optimize API Development Request Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/examples/example-prompts.md Use this prompt to generate requirements for a production-ready RESTful API. It details architectural needs, core endpoints, and technical specifications. ```plaintext create REST API for user management ``` -------------------------------- ### Check Authentication Status Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Verify the status of OAuth token and API key for authentication. If neither is set, run 'claude login'. ```bash echo "OAuth token: ${CLAUDE_CODE_OAUTH_TOKEN:+set}" echo "API key: ${ANTHROPIC_API_KEY:+set}" ``` -------------------------------- ### Test Optimized Prompt Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/README.md Use the '' tag followed by your prompt to test the functionality of the Claude Code Prompt Optimizer. ```bash write a function to calculate fibonacci numbers ``` -------------------------------- ### Debug Specific Optimizations Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Enable debug logging to see detailed logs for all optimizations. This is useful for diagnosing specific optimization issues. ```bash export DEBUG=true # Now all optimizations will be logged ``` -------------------------------- ### Advanced Optimization Prompt Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Combine the `` tag with specific requirements for more targeted prompt generation, such as security features. ```plaintext create a secure API with rate limiting and JWT auth ``` -------------------------------- ### Optimize Bug Fix Request Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/examples/example-prompts.md Use this prompt to generate a structured debugging and remediation framework for a specific bug. It outlines diagnostic and implementation phases. ```plaintext fix the login bug ``` -------------------------------- ### Verify Hook Permissions Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Ensure the hook script has execute permissions. The output should show execute permissions (x). ```bash ls -la src/hooks/optimize-prompt.sh # Should show: -rwxr-xr-x (with x for execute) ``` -------------------------------- ### Optimize Code Refactoring Request Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/examples/example-prompts.md Use this prompt to generate a systematic code refactoring strategy. It includes phases for code analysis, implementation, and validation to improve quality and performance. ```plaintext refactor this messy code ``` -------------------------------- ### Build Clean Environment for Subprocess Source: https://context7.com/johnpsasser/claude-code-prompt-optimizer/llms.txt Constructs a sanitized copy of process.env for spawning subprocesses. Removes the CLAUDECODE guard and clears API key sources to ensure authentication falls back to stored OAuth. ```typescript function buildCleanEnv(): Record { const env = { ...process.env }; // Remove guard that blocks nested claude invocations inside Claude Code delete env.CLAUDECODE; // Force OAuth fallback by clearing all API key vectors env.ANTHROPIC_API_KEY = ''; delete env.CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR; return env; } // The returned env is passed directly to query() options const q = query({ prompt: "...", options: { env: buildCleanEnv(), ... } }); ``` -------------------------------- ### Manual Hook Registration in Claude Code Source: https://context7.com/johnpsasser/claude-code-prompt-optimizer/llms.txt Manually register the hook by adding a 'UserPromptSubmit' entry to your '~/.claude/settings.json' file, pointing to the absolute path of the shell wrapper script. ```json { "hooks": { "UserPromptSubmit": [ { "hooks": [ { "type": "command", "command": "/home/user/projects/claude-code-prompt-optimizer/src/hooks/optimize-prompt.sh" } ] } ] } } ``` -------------------------------- ### Shell Wrapper for Prompt Optimization Hook Source: https://context7.com/johnpsasser/claude-code-prompt-optimizer/llms.txt The Bash entry point for Claude Code hooks. It sources nvm, optionally logs debug information, and delegates to optimize-prompt.ts using npx tsx. Debug logging is enabled via the DEBUG environment variable. ```bash #!/bin/bash # Enable debug logging export DEBUG=true # All hook calls and results are appended to this log file tail -f /tmp/claude-code-hook-debug.log # Test the hook directly from the command line echo '{ "prompt": " create a REST API", "session_id": "manual-test", "transcript_path": "/tmp/test", "hook_event_name": "UserPromptSubmit" }' | bash src/hooks/optimize-prompt.sh # Expected stdout (JSON consumed by Claude Code): # {"systemMessage":"----...\nOptimized Prompt:\n\nDesign and implement a production-ready RESTful API...","hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"..."}} ``` -------------------------------- ### Specific Bug Fix Prompt Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/examples/example-prompts.md Provide specific details within the tag to address particular bugs, such as login issues in an OAuth flow. ```plaintext fix the login bug in the OAuth flow ``` -------------------------------- ### Strip `` Tag from Prompt with `stripOptimizeTag` Source: https://context7.com/johnpsasser/claude-code-prompt-optimizer/llms.txt Removes ``, ``, and `` tags from a prompt string, trimming whitespace. Use this to clean the prompt before sending it for optimization. ```typescript function stripOptimizeTag(prompt: string): string { return prompt.replace(/<\/?optimize\/?>/gi, '').trim(); } ``` ```typescript // Examples stripOptimizeTag(" write a fibonacci function"); // → "write a fibonacci function" stripOptimizeTag("fix the login bug"); // → "fix the login bug" stripOptimizeTag(" refactor this codebase "); // → "refactor this codebase" ``` -------------------------------- ### Test Optimizer Standalone Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Test the optimizer script directly using Node.js and tsx. This allows testing without running through Claude Code. ```bash # Interactive test node -e " const input = { prompt: ' create a REST API', session_id: 'test', transcript_path: '/tmp/test', hook_event_name: 'UserPromptSubmit' }; console.log(JSON.stringify(input)); " | npx tsx src/hooks/optimize-prompt.ts ``` -------------------------------- ### Verify Hook Triggering Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/QUICKSTART.md Check if Claude Code recognizes the hook by viewing the settings.json file. Test the hook directly with a sample input. ```bash cat ~/.claude/settings.json ``` ```bash echo '{"prompt": " test", "session_id": "test", "transcript_path": "/tmp/test", "hook_event_name": "UserPromptSubmit"}' | bash src/hooks/optimize-prompt.sh ``` -------------------------------- ### Detect Prompt Optimization Trigger with `shouldOptimize` Source: https://context7.com/johnpsasser/claude-code-prompt-optimizer/llms.txt Checks if a prompt contains the case-insensitive `` tag. This function determines if the prompt should be processed for optimization or passed through unchanged. ```typescript function shouldOptimize(prompt: string): boolean { return //i.test(prompt); } ``` ```typescript // Truthy examples shouldOptimize(" build a REST API"); // true shouldOptimize(" fix the login bug"); // true shouldOptimize("refactor this function"); // true // Falsy — hook passes prompt through unchanged shouldOptimize("build a REST API"); // false shouldOptimize(" do something"); // false ``` -------------------------------- ### Hook Input/Output Schemas for Claude Code Source: https://context7.com/johnpsasser/claude-code-prompt-optimizer/llms.txt Defines the TypeScript interfaces for `HookInput` received from Claude Code and `HookOutput` sent back. Use `HookInput` to understand incoming prompts and `HookOutput` to structure the response, including optional prompt blocking or optimized content. ```typescript interface HookInput { session_id: string; transcript_path: string; hook_event_name: string; prompt: string; } ``` ```typescript interface HookOutput { decision?: 'block'; reason?: string; systemMessage?: string; hookSpecificOutput?: { hookEventName: string; additionalContext?: string; }; } ``` ```typescript const exampleInput: HookInput = { prompt: " create a user authentication system with JWT tokens", session_id: "example-session-001", transcript_path: "/tmp/claude-transcript", hook_event_name: "UserPromptSubmit" }; ``` ```typescript const exampleOutput: HookOutput = { systemMessage: "----...\nOptimized Prompt:\n\nDesign and implement a production-ready JWT authentication system...", hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: "----...\nOptimized Prompt:\n\n..." } }; ``` ```typescript const passthroughOutput: HookOutput = { hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: "create a user authentication system with JWT tokens" } }; ``` -------------------------------- ### Preserve Naming with Quotes Source: https://github.com/johnpsasser/claude-code-prompt-optimizer/blob/main/examples/example-prompts.md Use quotes within the tag to ensure that specific function names or identifiers are preserved exactly as provided. ```plaintext create a function called "processUserData" that validates input ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.