Claude Code Prompt Improver

repository·main·Indexed 23 days ago

https://github.com/severity1/claude-code-prompt-improver

An intelligent prompt optimization tool for Claude Code that injects context during prompt submission, tool use, and subagent starts. It uses a declarative hook engine and JSON-based 'nudges' to reduce correction turns by evaluating prompt clarity and providing targeted guidance or research-driven clarifying questions via the prompt-improver skill.

Tokens
11.8K
Snippets
24
Records
48
Agent score
82%

What's inside claude-code-prompt-improver

  1. Decision patterns for prompt evaluation

    main

    The prompt improver categorizes prompts into three decision paths:

    DecisionCondition
    PROCEED IMMEDIATELYTarget, Action, Criteria, and Context are all clearly defined or provided via system context (file view/error history).
    RESEARCH AND ASKGeneric verbs (e.g., "fix", "improve") are used without a target, or multiple valid architectural approaches exist.
    PASS THROUGHA bypass prefix (*, /, or #) is detected.
  2. Explore codebase patterns with the Explore Agent

    main

    When you need to understand architecture, find similar implementations, or explore unknown territory, use the Task tool with subagent_type=Explore.

    This approach allows you to:

    • Map codebase structure
    • Find similar implementations
    • Understand architectural patterns
    • Identify relevant components
    # Example Prompt: "find the bug"
    
    Research:
    1. Launch Explore agent: "Find error handling patterns in authentication code"
    2. Results: Discover auth.ts, middleware.ts, session.ts with different error patterns
    3. Finding: Inconsistent error handling across auth files
  3. Mine conversation history for context

    main

    Always review recent conversation history as a first research step. Look for:

    • Error messages in recent messages.
    • File names mentioned by the user.
    • Features being discussed.
    • Decisions already made.
    • Code snippets shown or referenced.

    Additionally, monitor File View Context (system messages indicating which file the user has opened) to understand their current focus area.

  4. Principles for constructing effective clarifying questions

    main

    When formulating questions to clarify user intent, follow these core principles to ensure they are actionable and research-driven:

    • Ground in Research: Options must be derived from actual findings (codebase exploration, documentation, web search, or git history).
    • Be Specific: Avoid generic options. Instead of "Use a different approach", use "Use JWT tokens with HttpOnly cookies".
    • Provide Context: Include trade-offs, implications, and reasons for each option in the description.
    • Stay Focused: Limit each question to a single decision point. Do not combine "Which file and what approach?"; split them into two questions.
    • Enable Choice: Provide between 2 and 4 options. Fewer than 2 is not a choice; more than 4 is overwhelming.

    Question Quality Checklist

    • Research phase is complete and findings are documented.
    • Each option is based on research, not assumptions.
    • Each option is specific and actionable.
    • Context and trade-offs are included in descriptions.
    • Questions are independent (can be answered in any order).
    • Total questions are between 1 and 6 based on complexity.
  5. How Prompt Improver Nudges Work

    main

    The plugin uses a set of targeted 'nudges' that fire based on specific conditions to provide context and prevent correction loops.

    Always-on Nudges:

    • improve: Evaluates every prompt for clarity. If vague, it invokes the prompt-improver skill to research and ask 1-6 grounded questions. If clear, it has zero overhead.
    • plan-mode: Evaluates every prompt to see if the task is complex enough to warrant a plan before acting. It self-cancels for trivial tasks.

    Conditional Nudges:

    • approach-assessment: Fires when a request looks non-trivial (e.g., implement, refactor, migrate) to decide on orchestration (subagent vs direct).
    • workflow: Fires for multi-step workflows to provide plan-first and model-routing guidance.
    • output-readability: Fires when a substantial deliverable is expected to enforce structure (sections, tables, terse conclusions).
    • ask-user-question: Fires when a request contains a decision that requires user input (tradeoffs, missing requirements).
    • plan: Fires specifically when entering plan-mode to provide a terse, readable plan.
    • background-exec: Fires before long-running commands (dev servers, watchers) to suggest running them in the background.
    • subagent-routing: Fires when a research or planning subagent starts to favor breadth over depth.
  6. How the prompt improver handles vague prompts

    main

    When a prompt is too vague (e.g., implement caching), the improver will not attempt to guess. Instead, it follows a Research and Ask pattern:

    1. Research: It explores the codebase to identify bottlenecks, existing implementations, and available libraries.
    2. Findings: It compiles a summary of what it discovered (e.g., identifying slow endpoints or existing Redis installations).
    3. Structured Questions: It presents the user with a set of structured, actionable questions (often using multiSelect or single-choice options) to resolve unknowns regarding targets, strategies, and configurations.

    This ensures that complex architectural changes are implemented according to your specific requirements rather than assumptions.

  7. Understand the Prompt Improver Skill workflow

    main

    The prompt-improver skill is designed to transform vague or ambiguous prompts into actionable requests. It follows a systematic 4-phase workflow:

    1. Phase 1: Research: Create a dynamic research plan using TodoWrite. You must check conversation history first, then review the codebase (using Task/Explore for architecture, Grep/Glob for patterns, git log for changes, or searching for errors/TODOs), and gather additional context via local docs or web searches. Never skip research.
    2. Phase 2: Generate Targeted Questions: Formulate 1-6 questions based on research findings. Questions should be grounded in research, specific, provided as multiple-choice (2-4 options), and focused on a single decision point.
    3. Phase 3: Get Clarification: Present the questions to the user using the AskUserQuestion tool.
    4. Phase 4: Execute with Context: Execute the original request by combining the original intent, the user's clarification answers, research findings, and conversation history.

    Key Principle: Always ground questions in actual findings from the research phase rather than assumptions or general knowledge.

  8. Understand the Prompt Improvement Workflow

    main

    The prompt improvement process follows a structured lifecycle to transform vague user inputs into actionable technical tasks. When a prompt is identified as 'vague' (lacking a clear target, action, or criteria), the system follows these steps:

    1. Evaluation: Assessing the prompt for Target, Action, Criteria, and Context.
    2. Research Plan: Defining what needs to be investigated (e.g., searching for TODOs, checking tests, or reviewing git history).
    3. Research Execution: Performing technical tasks like grep, glob, bash commands, or webSearch to gather facts.
    4. Research Findings: Summarizing the discovered information.
    5. Questions Asked: Using the AskUserQuestion tool to present structured options to the user.
    6. User Answers: Receiving specific selections from the user.
    7. Execution: Fulfilling the request based on the refined context.
  9. How the Prompt Improver architecture works

    main

    The project uses a declarative hook engine driven by a JSON nudge registry.

    Core Components

    • Engine (scripts/engine.py): An event dispatcher invoked as engine.py <EventName>. It reads stdin, runs rules for the event, merges inject_context fragments by priority, and emits a hookSpecificOutput object.
    • Rules (scripts/rules.py): Loads and validates nudges/*.json. It manages the event-to-capability matrix (e.g., inject_context is available on UserPromptSubmit, PreToolUse, and SubagentStart).
    • Builtins (scripts/nudge_builtins.py): An escape hatch providing allowlisted HANDLERS (like improve or workflow) and MATCHERS (like saved_workflow_exists).
    • Nudges (nudges/*.json): The registry of capabilities. Each nudge is a JSON file that defines criteria (regex matching) and an action (injecting context or running a handler).

    Execution Flow

    1. Clear Prompts: The hook evaluates the prompt (~189 tokens). If clear, Claude proceeds immediately with zero skill overhead.
    2. Vague Prompts: If the prompt is vague, Claude invokes the prompt-improver skill, which loads research/question guidance to help clarify the task.
  10. Use the Research Planning Framework

    main

    Before performing research, follow this four-phase framework to ensure systematic investigation and avoid missing critical context.

    1. Identify What's Unclear: Explicitly define gaps in Target (which file/function?), Approach (how to implement?), Scope (how much to change?), and Context (current state/existing patterns).
    2. Create Research Plan with TodoWrite: Use the TodoWrite tool to generate a structured plan before executing.
    3. Execute Research: Systematically perform each step in the plan.
    4. Document Findings: Summarize key files, existing patterns, common approaches, best practices, and discovered constraints.
    Research Plan for [Prompt Type]:
    1. [What to research] - [Tool/approach]
    2. [What to research] - [Tool/approach]
    3. [What to research] - [Tool/approach]
  11. Research guidelines for prompt enrichment

    main

    When performing the Research phase of the prompt-improver skill, follow these rules to ensure high-quality context:

    • Prioritize History: Check conversation history before exploring the codebase to avoid redundant work.
    • Use Task/Explore: Route Glob, Grep, WebSearch, WebFetch, and multi-file Read operations through Task/Explore. Do not call these tools directly in the main context.
    • Provide Context to Explore: Because Explore cannot see prior conversation turns, you must include conversation-relevant context (file paths, specific errors, or prior decisions) in every Explore prompt.
    • Research Plan Template:
      1. Check conversation history.
      2. Review codebase (Architecture via Task/Explore, patterns via Grep/Glob, changes via git log, or issues via error/TODO searches).
      3. Gather additional context (Local docs or WebFetch/WebSearch).
      4. Document findings to ground subsequent questions.