Skip to content
Back to search

claude-code-prompt-improver

Intelligent prompt improver hook for Claude Code. Type vibes, ship precision.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/severity1-claude-code-prompt-improver/badge.svg)](/listings/severity1-claude-code-prompt-improver)

HTML

<a href="/listings/severity1-claude-code-prompt-improver"><img src="/api/listings/severity1-claude-code-prompt-improver/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

**Requirements:** Claude Code 2.0.22+ (uses AskUserQuestion tool for targeted clarifying questions)

Option 1: Via Marketplace (Recommended)

**1. Add the marketplace:**

claude plugin marketplace add severity1/severity1-marketplace

**2. Install the plugin:**

claude plugin install prompt-improver@severity1-marketplace

**3. Restart Claude Code**

Verify installation with `/plugin` command. You should see the prompt-improver plugin listed.

Option 2: Local Plugin Installation (Recommended for Development)

**1. Clone the repository:**

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

**2. Add the local marketplace:**

claude plugin marketplace add /absolute/path/to/claude-code-prompt-improver/.dev-marketplace/.claude-plugin/marketplace.json

Replace `/absolute/path/to/` with the actual path where you cloned the repository.

**3. Install the plugin:**

claude plugin install prompt-improver@local-dev

**4. Restart Claude Code**

Verify installation with `/plugin` command. You should see "1 plugin available, 1 already installed".

Option 3: Manual Installation

**1. Copy the engine, rules, builtins, and nudges:**

mkdir -p ~/.claude/hooks/prompt-improver/scripts
cp scripts/engine.py scripts/rules.py scripts/nudge_builtins.py ~/.claude/hooks/prompt-improver/scripts/
cp -r nudges ~/.claude/hooks/prompt-improver/nudges
chmod +x ~/.claude/hooks/prompt-improver/scripts/engine.py

The engine resolves `nudges/` relative to its own location and loads it recursively (`nudges/<EventName>/*.json`), so copy the whole `nudges/` tree and keep `scripts/` and `nudges/` siblings under the same parent.

**2. Update `~/.claude/settings.json`:**

{
  "hooks": {
    "UserPromptSubmit": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "python3 ~/.claude/hooks/prompt-improver/scripts/engine.py UserPromptSubmit"
          }
        ]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "EnterPlanMode|Bash",
        "hooks": [
          {
            "type": "command",
            "command": "python3 ~/.claude/hooks/prompt-improver/scripts/engine.py PreToolUse"
          }
        ]
      }
    ],
    "SubagentStart": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "python3 ~/.claude/hooks/prompt-improver/scripts/engine.py SubagentStart"
          }
        ]
      }
    ]
  }
}

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 391 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # Claude Code Prompt Improver
  2. Intelligent prompt optimization for Claude Code. It injects the right context at the right moment - at prompt submit, tool use, and subagent start - so Claude has what it needs before it acts. The goal is a better first output, so you spend fewer turns correcting it.
  3. Prompt improvement here means improving the whole path from your prompt to Claude's output, not just rewriting the words you typed. Clarifying a vague prompt is one way to do that. Supplying a constraint you would otherwise have had to add by hand after a bad first attempt is another. Both land the output sooner.
  4. ![Demo](assets/demo.gif)
  5. ## What It Does
  6. A small set of targeted nudges fire only when they apply, each one supplying context that would otherwise cost a correction round-trip:
  7. | Nudge | Fires when | Supplies |
  8. |-------|-----------|----------|
  9. | `improve` | every prompt (flagship) | clarity check; asks 1-6 grounded questions only when the prompt is genuinely vague |
  10. | `approach-assessment` | a request looks non-trivial (implement, refactor, migrate, multi-file) | choose how to carry it out - subagent, heavier orchestration, or just do it - and pass a spawned subagent the context it needs |
  11. | `workflow` | a request looks like a multi-step workflow | plan-first and per-stage model-routing guidance |
  12. | `output-readability` | the response will be a substantial deliverable | lead with the conclusion, prefer sections and tables, keep it terse |
  13. | `ask-user-question` | a request hides a decision that is genuinely yours (a fork, a real tradeoff, missing requirements) | ask via the AskUserQuestion tool with concrete options so you can think critically; research first when context is thin; default on minor or reversible choices |
  14. | `plan-mode` | every prompt (alongside `improve`) | assess whether the task is complex enough to warrant a plan reviewed before any code; enter plan mode if so, otherwise proceed |
  15. | `plan` | entering plan mode | terse, readable plan: file-path anchors, no decision history; re-read for flaws before presenting |
  16. | `background-exec` | a long-running command (dev server, watcher, tail) is about to run | run it in the background, poll only the output that matters |
  17. | `subagent-routing` | a research or planning subagent starts | favor breadth over depth, return conclusions not raw dumps |
  18. **Two nudges evaluate every prompt.** `improve` checks clarity:
  19. - For clear prompts: proceeds immediately (zero skill overhead)
  20. - For vague prompts: invokes the `prompt-improver` skill to create a research plan, gather context, and ask 1-6 grounded questions, then proceeds with the clarification
  21. `plan-mode` runs alongside it, judging whether the task is complex enough to plan before acting - it self-cancels on anything trivial.
  22. The other seven fire only when they apply. The keyword-gated ones (`workflow`, `approach-assessment`, `output-readability`, `ask-user-question`, `background-exec`) lead with a condition ("If this is X... if not, ignore"), so a false fire is dismissed cheaply; the exact-gated ones (`plan` on plan-mode entry, `subagent-routing` on a research agent) only fire when the condition is already certain.
  23. **Result:** Better outcomes on the first try, without back-and-forth.
  24. **v0.4.0 Update:** Skill-based architecture with hook-level evaluation achieves 31% token reduction. Clear prompts have zero skill overhead, vague prompts get comprehensive research and questioning via the skill.
  25. ## How It Works
  26. ```mermaid
  27. sequenceDiagram
  28. participant User
  29. participant Hook
  30. participant Claude
  31. participant Skill
  32. participant Explore
  33. participant Project
  34. User->>Hook: "fix the bug"
  35. Hook->>Claude: Evaluation prompt (~189 tokens)
  36. Claude->>Claude: Evaluate using conversation history
  37. alt Vague prompt
  38. Claude->>Skill: Invoke prompt-improver skill
  39. Skill-->>Claude: Research and question guidance
  40. Claude->>Claude: Create research plan (TodoWrite)
  41. Claude->>Explore: Dispatch research (Glob, Grep, Web, multi-file Read)
  42. Explore->>Project: Execute search and reads
  43. Project-->>Explore: Raw results
  44. Explore-->>Claude: Synthesized findings
  45. Claude->>Claude: Synthesize, mine history, run git/Bash if needed
  46. Claude->>User: Ask grounded questions (1-6)
  47. User->>Claude: Answer
  48. Claude->>Claude: Execute original request with answers
  49. else Clear prompt
  50. Claude->>Claude: Proceed immediately (no skill load)
  51. end
  52. ```
  53. ## Installation
  54. **Requirements:** Claude Code 2.0.22+ (uses AskUserQuestion tool for targeted clarifying questions)
  55. ### Option 1: Via Marketplace (Recommended)
  56. **1. Add the marketplace:**
  57. ```bash
  58. claude plugin marketplace add severity1/severity1-marketplace
  59. ```
  60. **2. Install the plugin:**
  61. ```bash
  62. claude plugin install prompt-improver@severity1-marketplace
  63. ```
  64. **3. Restart Claude Code**
  65. Verify installation with `/plugin` command. You should see the prompt-improver plugin listed.
  66. ### Option 2: Local Plugin Installation (Recommended for Development)
  67. **1. Clone the repository:**
  68. ```bash
  69. git clone https://github.com/severity1/claude-code-prompt-improver.git
  70. cd claude-code-prompt-improver
  71. ```
  72. **2. Add the local marketplace:**
  73. ```bash
  74. claude plugin marketplace add /absolute/path/to/claude-code-prompt-improver/.dev-marketplace/.claude-plugin/marketplace.json
  75. ```
  76. Replace `/absolute/path/to/` with the actual path where you cloned the repository.
  77. **3. Install the plugin:**
  78. ```bash
  79. claude plugin install prompt-improver@local-dev
  80. ```
  81. **4. Restart Claude Code**
  82. Verify installation with `/plugin` command. You should see "1 plugin available, 1 already installed".
  83. ### Option 3: Manual Installation
  84. **1. Copy the engine, rules, builtins, and nudges:**
  85. ```bash
  86. mkdir -p ~/.claude/hooks/prompt-improver/scripts
  87. cp scripts/engine.py scripts/rules.py scripts/nudge_builtins.py ~/.claude/hooks/prompt-improver/scripts/
  88. cp -r nudges ~/.claude/hooks/prompt-improver/nudges
  89. chmod +x ~/.claude/hooks/prompt-improver/scripts/engine.py
  90. ```
  91. The engine resolves `nudges/` relative to its own location and loads it recursively (`nudges/<EventName>/*.json`), so copy the whole `nudges/` tree and keep `scripts/` and `nudges/` siblings under the same parent.
  92. **2. Update `~/.claude/settings.json`:**
  93. ```json
  94. {
  95. "hooks": {
  96. "UserPromptSubmit": [
  97. {
  98. "hooks": [
  99. {
  100. "type": "command",
  101. "command": "python3 ~/.claude/hooks/prompt-improver/scripts/engine.py UserPromptSubmit"
  102. }
  103. ]
  104. }
  105. ],
  106. "PreToolUse": [
  107. {
  108. "matcher": "EnterPlanMode|Bash",
  109. "hooks": [
  110. {
  111. "type": "command",
  112. "command": "python3 ~/.claude/hooks/prompt-improver/scripts/engine.py PreToolUse"
  113. }
  114. ]
  115. }
  116. ],
  117. "SubagentStart": [
  118. {
  119. "hooks": [
  120. {
  121. "type": "command",
  122. "command": "python3 ~/.claude/hooks/prompt-improver/scripts/engine.py SubagentStart"
  123. }
  124. ]
  125. }
  126. ]
  127. }
  128. }
  129. ```
  130. ## Usage
  131. **Normal use:**
  132. ```bash
  133. claude "fix the bug" # Hook evaluates, may ask questions
  134. claude "add tests" # Hook evaluates, may ask questions
  135. ```
  136. **Bypass prefixes:**
  137. ```bash
  138. claude "* add dark mode" # * = skip evaluation
  139. claude "/help" # / = slash commands bypass
  140. claude "# remember to use rg over grep" # # = memorize bypass
  141. ```
  142. Harness messages that arrive as prompts (for example `<task-notification>` or `<system-reminder>`) also bypass every prompt nudge.
  143. **Vague prompt:**
  144. ```bash
  145. $ claude "fix the error"
  146. ```
  147. Claude asks:
  148. ```
  149. Which error needs fixing?
  150. ○ TypeError in src/components/Map.tsx (recent change)
  151. ○ API timeout in src/services/osmService.ts
  152. ○ Other (paste error message)
  153. ```
  154. You select an option, Claude proceeds with full context.
  155. **Clear prompt:**
  156. ```bash
  157. $ claude "Fix TypeError in src/components/Map.tsx line 127 where mapboxgl.Map constructor is missing container option"
  158. ```
  159. Claude proceeds immediately without questions.
  160. ## Design Philosophy
  161. - **Improve the prompt-to-output path** - the goal is a right first output. Clarifying a vague prompt is one way; injecting a constraint the user would otherwise add by hand after a bad attempt is another. Both count.
  162. - **Rarely intervene** - most prompts pass through unchanged; each nudge fires only when it applies.
  163. - **Fire wide, self-cancel cheap** - a missed nudge costs a full correction loop, a false fire costs a few tokens Claude ignores. That asymmetry justifies high-recall gates, so every nudge leads with a condition ("If this is X... if not, ignore") and dismisses itself when it does not fit.
  164. - **Trust user intent** - only ask when genuinely unclear; never block.
  165. - **Max 1-6 questions** - enough for complex scenarios, still focused.
  166. - **Transparent** - injected context is visible in the conversation.
  167. ## Architecture
  168. **Declarative hook engine driven by a JSON nudge registry.** One engine dispatches every hook event; each capability is a data row in `nudges/*.json`, not a separate script. Adding an inject-context nudge is a single JSON file with zero Python changes.
  169. **Engine (scripts/engine.py) - Event Dispatcher:**
  170. - Invoked as `engine.py <EventName>` (one entry per event in `hooks.json`)
  171. - Reads stdin once, runs the event's rules, merges `inject_context` fragments by `priority` with a blank-line join, emits one `hookSpecificOutput` object
  172. - Exits 0 on every path - a missing/unknown event or an event with no rules is a clean no-op that never reads stdin
  173. - One bad rule is isolated in a `try/except` so it cannot suppress the others
  174. **Rules (scripts/rules.py) - Loader + Validation:**
  175. - Loads and validates `nudges/*.json`; invalid rows are skipped with a stderr note (loading never raises into the engine)
  176. - `validate_rule` enforces: required `id`/`event`, known event, `action` XOR `handler`, action type legal for the event, compilable regexes, allowlisted `builtin`/`handler` names, unique id
  177. - Owns the event->capability matrix (v1: `inject_context` on `UserPromptSubmit`, `PreToolUse`, `SubagentStart`)
  178. - Regexes are compiled once per dispatched event, not at file load
  179. **Builtins (scripts/nudge_builtins.py) - Escape Hatch:**
  180. - Two allowlist dicts referenced by string name only: `HANDLERS` (`improve`, `workflow`) and `MATCHERS` (`saved_workflow_exists`)
  181. - A rule with `"handler": "improve"` runs the named handler, which owns its full fragment including bypass logic; a rule with `"criteria": {"builtin": "saved_workflow_exists"}` runs the named matcher
  182. - No `eval`/`importlib`/`getattr`-on-path: an unknown name is a load-time skip, never an arbitrary import
  183. - Named `nudge_builtins` (not `builtins`) because the stdlib `builtins` module is loaded before any user code and would permanently shadow a local `builtins.py`
  184. **Nudges (nudges/*.json) - The Registry:**
  185. - `improve` - checks whether a submitted prompt is clear enough to act on, and asks for clarification only when it is genuinely vague.
  186. - `approach-assessment` - when a request looks non-trivial, raises how to carry it out (a subagent, heavier orchestration, or just doing it) and reminds that a spawned subagent needs its context passed explicitly.
  187. - `workflow` - when a request looks like a multi-step workflow, suggests planning before running and routing each stage to an appropriately sized model.
  188. - `ask-user-question` - when a request hides a decision that is genuinely the user's (a fork, a real tradeoff, missing requirements), routes it through the AskUserQuestion tool with concrete options, grounds the questions in research when context is thin, and defaults on minor or reversible choices.
  189. - `plan-mode` - evaluates every prompt: judges whether the task is complex, multi-step, ambiguous, or architectural enough to warrant a plan reviewed before any code is written, and enters plan mode if so. Self-cancels on trivial work. Owns "whether to plan at all"; `approach-assessment` owns "which approach".
  190. - `plan` - when entering plan mode, encourages a clean, readable plan: terse steps, file-path anchors, no decision history, and a re-read for flaws before presenting.
  191. - `subagent-routing` - when a research or planning subagent starts, encourages breadth over depth and lean, conclusion-first reporting.
  192. - `background-exec` - when a long-running command (dev server, watcher, tail) is about to run, suggests running it in the background and polling only the output that matters.
  193. - `output-readability` - when the response will be a substantial deliverable (report, review, summary, analysis), encourages a human-readable result: lead with the conclusion, prefer sections and tables, keep it terse.
  194. **Known limitation (workflow nudge):** the keyword filter biases toward recall, so a non-launch mention of "workflow" (e.g. "fix the CI workflow file") may inject inert guidance. The guidance leads with a conditional guard ("If this prompt will run as a dynamic workflow... if not, ignore") so the model self-cancels false positives. No hook can see the post-prompt workflow decision.
  195. **Skill (skills/prompt-improver/) - Research & Question Logic:**
  196. - **SKILL.md**: Research and question workflow (~170 lines)
  197. - Assumes prompt already determined vague by the engine's improve nudge
  198. - 4-phase process: Research → Questions → Clarify → Execute
  199. - Links to reference files for progressive disclosure
  200. - **references/**: Detailed guides loaded on-demand
  201. - `question-patterns.md`: Question templates (200-300 lines)
  202. - `research-strategies.md`: Context gathering (300-400 lines)
  203. - `examples.md`: Real transformations (200-300 lines)
  204. ## How to Add a Nudge
  205. A new inject-context nudge is a single JSON file under `nudges/` - no Python changes.
  206. **1. Drop a file in the event's subdirectory.** Nudges live in `nudges/<EventName>/`, one folder per hook event, and files are named `<priority>-<id>.json` so each folder sorts in merge order:
  207. ```
  208. nudges/
  209. UserPromptSubmit/
  210. 00-improve.json
  211. 10-approach-assessment.json
  212. 20-workflow.json
  213. 30-output-readability.json
  214. 40-ask-user-question.json
  215. 50-plan-mode.json
  216. PreToolUse/
  217. 00-plan.json
  218. 10-background-exec.json
  219. SubagentStart/
  220. 00-subagent-routing.json
  221. ```
  222. For example, `nudges/UserPromptSubmit/20-kubernetes.json`:
  223. ```json
  224. {
  225. "id": "kubernetes",
  226. "event": "UserPromptSubmit",
  227. "description": "What this nudge does and why (never emitted - JSON has no comments).",
  228. "criteria": {
  229. "match": ["\\bkubernetes\\b"],
  230. "flags": ["ignorecase"],
  231. "non_slash": true
  232. },
  233. "action": {
  234. "type": "inject_context",
  235. "text": [
  236. "If this task touches Kubernetes manifests: validate with kubeconform before applying.",
  237. "If not, ignore this guidance."
  238. ]
  239. },
  240. "priority": 20
  241. }
  242. ```
  243. The parent directory is authoritative: a rule whose `event` field does not match its folder is skipped with a stderr note (so a file in `PreToolUse/` cannot claim `"event": "UserPromptSubmit"`). The filename's priority prefix is cosmetic - the engine sorts fragments by the JSON `priority` field, not the filename, so keep the two in sync. Priority is event-scoped: it only orders rules that share an event (e.g. `improve` at 0 and `workflow` at 20 both merge on `UserPromptSubmit`; `plan` at 0 never competes with them). Pad the prefix to match your widest priority (2 digits is safe for the gap convention 0/10/20/.../50; a priority >= 100 sorts wrong against 2-digit names).
  244. **2. That's it.** The engine recursively auto-loads every `nudges/**/*.json` on the next prompt. No `hooks.json` edit is needed unless the nudge targets a new event (each event needs one dispatch entry in `hooks.json` and one new `nudges/<EventName>/` folder).
  245. **Schema reference:**
  246. | Field | Required | Meaning |
  247. |-------|----------|---------|
  248. | `id` | yes | Unique rule id |
  249. | `event` | yes | `UserPromptSubmit`, `PreToolUse`, or `SubagentStart` |
  250. | `description` | no | Intent note, never emitted |
  251. | `action` | one of | `{ "type": "inject_context", "text": [lines], "append_when": [{ "match": [regex], "text": [lines] }] }` |
  252. | `handler` | one of | String naming a callable in `nudge_builtins.HANDLERS` (escape hatch) |
  253. | `criteria` | no | `match`/`exclude` (regex arrays), `match_target` (`prompt`\|`tool_name`\|`agent_type`\|`command`; `command` reads nested `tool_input.command`), `non_slash`, `flags`, `builtin` |
  254. | `bypass` | no | `default` (suppress on `*`/`#`/empty/harness machine events for prompt targets) or `none` |
  255. | `priority` | no | Merge order (lower first); default 100 |
  256. Provide exactly one of `action` or `handler`. `text` is an array of lines joined with newlines at load (clean multiline diffs). `append_when` models a conditional clause declaratively (used by the ultracode clause). Invalid rows are skipped with a stderr note; the engine still exits 0.
  257. **Flow for Clear Prompts:**
  258. 1. Hook wraps with evaluation prompt (~189 tokens)
  259. 2. Claude evaluates: prompt is clear
  260. 3. Claude proceeds immediately (no skill invocation)
  261. 4. **Total overhead: ~189 tokens**
  262. **Flow for Vague Prompts:**
  263. 1. Hook wraps with evaluation prompt (~189 tokens)
  264. 2. Claude evaluates: prompt is vague
  265. 3. Claude invokes `prompt-improver` skill
  266. 4. Skill loads research/question guidance
  267. 5. Claude creates research plan, gathers context, asks questions
  268. 6. **Total overhead: ~189 tokens + skill load**
  269. **Progressive Disclosure Benefits:**
  270. - Clear prompts: Never load skill (zero skill overhead)
  271. - Vague prompts: Only load skill and relevant reference files
  272. - Detailed guidance available without bloating all prompts
  273. - Zero context penalty for unused reference materials
  274. **Research dispatch model:**
  275. - Glob, Grep, WebSearch, WebFetch, and multi-file Read route through `Task/Explore` (Haiku-based, separate context window)
  276. - Main context handles history mining, single-file Reads of user-named files, Bash/git commands, synthesis, and questions
  277. - Bash stays in main context because Explore agents cannot run shell commands
  278. - Every Explore dispatch carries explicit conversation context (file paths, errors, prior decisions) since Explore has no access to prior turns
  279. - Net effect: search noise lives in cheap subagent tokens, decisions live in main-context tokens
  280. **Manual Skill Invocation:**
  281. You can also invoke the skill manually without the hook:
  282. ```
  283. Use the prompt-improver skill to research and clarify: "add authentication"
  284. ```
  285. ## Token Overhead
  286. **v0.4.0 Update:** 31% reduction through hook-level evaluation
  287. - **Per prompt (v0.4.0):** ~189 tokens (evaluation prompt)
  288. - **Per prompt (v0.3.x):** ~275 tokens (embedded evaluation logic)
  289. - **Reduction:** ~86 tokens saved per prompt (31% decrease)
  290. - **30-message session:** ~5.7k tokens (~2.8% of 200k context, down from 4.1%)
  291. - **Trade-off:** Minimal overhead for better first-attempt results
  292. **Clear prompts benefit:**
  293. - Evaluation happens in hook (~189 tokens)
  294. - Claude proceeds immediately (no skill load)
  295. - Zero skill overhead for clear prompts
  296. **Vague prompts:**
  297. - Evaluation in hook (~189 tokens)
  298. - Skill loads only when needed for research/questions
  299. - Progressive disclosure: reference files load on-demand
  300. ## FAQ
  301. **Does this work on all prompts?**
  302. Yes, unless you use bypass prefixes (`*`, `/`, `#`).
  303. **Will it slow me down?**
  304. Only slightly when it asks questions. Faster overall due to better context.
  305. **Will I get bombarded with questions?**
  306. No. It rarely intervenes, passes through most prompts, and asks max 1-6 questions.
  307. **Can I customize behavior?**
  308. It adapts automatically using conversation history, dynamic research planning, and CLAUDE.md.
  309. **What if I don't want improvement?**
  310. Use `*` prefix: `claude "* your prompt here"`
  311. ## License
  312. MIT

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.