cco
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/listings/egorfedorov--claude-context-optimizer)HTML
<a href="/listings/egorfedorov--claude-context-optimizer"><img src="/api/listings/egorfedorov--claude-context-optimizer/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
**claude.ai, the desktop app and Cowork:** open the Directory, search for *Context Optimizer*, and add it.
**Claude Code**, from the plugin marketplace:
claude plugin marketplace add egorfedorov/claude-context-optimizer claude plugin install context-optimizer@cco
Then restart Claude Code.
**From a clone**, to change the plugin and see it live:
git clone https://github.com/egorfedorov/claude-context-optimizer.git ~/claude-context-optimizer claude --plugin-dir ~/claude-context-optimizer
Updating
claude plugin marketplace update cco claude plugin update context-optimizer@cco
Upgrading from 4.x
- **Commands moved under `/cco`** in 5.0: `/cco-audit` is now `/cco audit`, `/cco-task` is `/cco task`, and so on. `/cco help` lists them. - **The plugin was renamed** in 4.21 from `claude-context-optimizer` to `context-optimizer`, because Claude Code reserves the `claude-` prefix. Both marketplaces map the old name to the new one. If your install didn't move, reinstall once:
claude plugin uninstall claude-context-optimizer@cco claude plugin marketplace update cco claude plugin install context-optimizer@cco
Your history stays in `~/.claude-context-optimizer/`.
Requirements
- Claude Code with plugin support. Skills alone work on claude.ai and in Cowork. - Node.js 18 or later for the hooks and `/cco`. - A POSIX shell for hooks: macOS and Linux as they are, Git Bash or WSL on Windows.
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.
.claude-plugin/marketplace.json · Manifest · 20 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- {
- "name": "cco",
- "owner": {
- "name": "Egor Fedorov"
- },
- "metadata": {
- "description": "Context and cost tooling for Claude Code: the context-optimizer plugin (CCO)."
- },
- "renames": {
- "claude-context-optimizer": "context-optimizer"
- },
- "plugins": [
- {
- "name": "context-optimizer",
- "description": "See what Claude costs you and spend less of it. In chat: hand a long chat over to a new one, digest long documents, set up Projects, check tokens, sharpen prompts. In Claude Code: Haiku 5.5 subagents for reading and test runs; /cco audit of your own transcripts. Local, no telemetry.",
- "version": "5.1.1",
- "source": "./"
- }
- ]
- }
README.md · README · 239 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- # Context Optimizer (CCO)
- **See what Claude costs you, and spend less of it.** Every message re-sends
- the whole conversation, so long chats and long coding sessions use up limits
- fast and recall early details worse. context-optimizer keeps the context small,
- moves cheap work to a cheap model, and shows you the numbers while you work.
- | Where | What you get |
- |---|---|
- | **claude.ai chat and desktop** | Skills Claude uses on its own: `fresh-start` hands a long chat over to a new one, `doc-digest` turns a long document into a working digest, `project-context` turns background you keep retyping into Project instructions, `token-check` sizes text and files, `sharpen-prompt` tightens a vague request |
- | **Cowork** | The same skills, plus two subagents on Haiku 5.5, about 40× cheaper than Opus: `scout` for reading and searching, `runner` for tests and builds |
- | **Claude Code** | Everything: the Haiku subagents, `/cco` (a session board, an audit of your own transcripts, task state that survives `/compact`, and more), read dedup, and budget and cache warnings |
- Runs locally, open source (MIT), no telemetry.
- 
- [](#installation)
- [](LICENSE)
- 
- [](https://github.com/hesreallyhim/awesome-claude-code)
- ---
- ## Skills that work everywhere
- These need no setup and run in chat, Cowork and Claude Code alike. Claude
- picks them up on its own, or you can ask:
- | Skill | Ask for it like this | What you get |
- |---|---|---|
- | `fresh-start` | "Let's continue in a new chat" | A handoff under 300 words to paste into a new conversation, with how much it saves |
- | `doc-digest` | "Summarize this so we can keep working with it" | A digest of a long document, with a section map and references, at a tenth of the size |
- | `project-context` | "I keep explaining the same thing" | Instructions and a file list for a Project, Cowork folder or `CLAUDE.md`, so new chats start with it |
- | `token-check` | "How many tokens is this?" | A size estimate, what it costs over a conversation, and how to cut it |
- | `sharpen-prompt` | "Improve this prompt" | The same request with goal, scope, constraints and what done looks like |
- ## In Claude Code
- ### Haiku subagents
- | Agent | Model | Use |
- |---|---|---|
- | `context-optimizer:scout` | Haiku 5.5 | Read-only exploration of the project: several files, wide searches. Read, Grep and Glob only. Returns a short answer with `path:line`. |
- | `context-optimizer:runner` | Haiku 5.5 | Test suites, builds, linters. Returns pass/fail and the failing items only. |
- A one-paragraph policy at session start (about 90 tokens, once per
- conversation) tells Claude when to hand work to them. Only their short answer
- enters the expensive model's context. `/cco orchestrate <task>` runs a whole
- task that way.
- ### `/cco`: one command for the rest
- `/cco` alone shows the session board: budget, money spent and saved, waste,
- the active task and what to do next. `/cco help` lists everything:
- | See where the tokens go | Spend less | Settings and data |
- |---|---|---|
- | `/cco audit`: your own transcripts, where the money went, what CCO saved; `/cco wrapped`: your week in one screen | `/cco orchestrate <task>`: Haiku does the reading and test runs | `/cco config`: thresholds |
- | `/cco report`, `/cco roi`, `/cco digest`: trends across sessions | `/cco task`: cost per task, state that survives `/compact` | `/cco budget`: budget and auto-compact |
- | `/cco replay`: recent sessions | `/cco pack <task>`: the files a task needs, with line ranges | `/cco export`: Markdown or an offline HTML page |
- | `/cco tools`: what each tool costs | `/cco anatomy`, `/cco git`: a project map, git-aware context | `/cco patterns`: share learned patterns |
- | `/cco overhead`: the fixed context every session starts with | `/cco claudemd`, `/cco shield`, `/cco coach`, `/cco templates` | `/cco clean`, `/cco doctor` |
- ### What runs on its own
- - **Read dedup.** A re-read of a file that hasn't changed, in the same context,
- is skipped, with a map of the file's landmarks instead. A changed file, a
- new range, or a read after `/compact` goes through.
- - **Budget and cache warnings** at 50/70/85/95% of the budget, and a note when
- a pause let the prompt cache go cold, with what that cost.
- - **Task state across `/compact`.** A small execution state you keep with
- `/cco task` is put back into context after compaction.
- - **A recap of the last session** in a project when you start the next one.
- - **`.contextignore`** keeps files you never need out of reads.
- ## Does it really save?
- We checked on real transcripts rather than guessing. In long Opus sessions
- about 60% of the cost is cache reads: the whole context re-read on every
- request. Repeated reads of unchanged files, which dedup removes, turned out to
- be rare. So the levers that matter are a smaller context and a cheaper model
- for the reading: the Haiku subagents, compacting at the right time, and not
- letting the cache go cold on a big context. `/cco audit` shows what that
- comes to in your own sessions, including what CCO's own messages cost.
- ---
- ## Installation
- **claude.ai, the desktop app and Cowork:** open the Directory, search for
- *Context Optimizer*, and add it.
- **Claude Code**, from the plugin marketplace:
- ```bash
- claude plugin marketplace add egorfedorov/claude-context-optimizer
- claude plugin install context-optimizer@cco
- ```
- Then restart Claude Code.
- **From a clone**, to change the plugin and see it live:
- ```bash
- git clone https://github.com/egorfedorov/claude-context-optimizer.git ~/claude-context-optimizer
- claude --plugin-dir ~/claude-context-optimizer
- ```
- ### Updating
- ```bash
- claude plugin marketplace update cco
- claude plugin update context-optimizer@cco
- ```
- ### Upgrading from 4.x
- - **Commands moved under `/cco`** in 5.0: `/cco-audit` is now `/cco audit`,
- `/cco-task` is `/cco task`, and so on. `/cco help` lists them.
- - **The plugin was renamed** in 4.21 from `claude-context-optimizer` to
- `context-optimizer`, because Claude Code reserves the `claude-` prefix. Both
- marketplaces map the old name to the new one. If your install didn't move,
- reinstall once:
- ```bash
- claude plugin uninstall claude-context-optimizer@cco
- claude plugin marketplace update cco
- claude plugin install context-optimizer@cco
- ```
- Your history stays in `~/.claude-context-optimizer/`.
- ### Requirements
- - Claude Code with plugin support. Skills alone work on claude.ai and in Cowork.
- - Node.js 18 or later for the hooks and `/cco`.
- - A POSIX shell for hooks: macOS and Linux as they are, Git Bash or WSL on
- Windows.
- ## Settings
- Everything lives in `~/.claude-context-optimizer/config.json`; `/cco config`
- shows and changes it.
- - `"orchestrate": false` turns off the session-start policy that sends work
- to the Haiku subagents.
- - `"quiet": true` hides the donation line and the prompt coach.
- - `thresholds` tunes the read-dedup and warning thresholds, each
- range-checked: `/cco config set staleTimeMs 300000`.
- ## Privacy
- This plugin:
- - **Tracks file paths and line counts**, never file contents
- - **Keeps a 200-character preview of each prompt** (with its grade) so `/cco coach` can show trends
- - **Reads token-usage numbers** from Claude Code's own session transcript to price the session; `/cco audit` reads your transcripts under `~/.claude/projects/` and prints only totals
- - **Runs `git` locally** for `/cco git`, `/cco pack` and `/cco anatomy`; nothing else is executed
- - **Stores everything locally** in `~/.claude-context-optimizer/`, pruned automatically (90 days for session history, 14 for live-session state)
- - **Sends zero telemetry**: the plugin's own code makes no network calls, no analytics, no tracking
- - **Reads no environment variables**: every setting lives in `~/.claude-context-optimizer/config.json`
- - **Ships two subagents** (`scout`, `runner`) that Claude can call. They use Claude Code's own tools under your permission settings: `scout` only reads and searches the project (Read, Grep, Glob), and `runner` runs the commands it is given through Bash
- - **`/cco export html` writes one offline file**: charts are inline SVG, with no scripts and nothing loaded from the web
- - **Can be fully wiped** with `/cco clean --reset-all`
- Your data never leaves your machine.
- ## FAQ
- **Does it slow Claude Code down?**
- Barely. Each hook event starts one Node process, about 50–65 ms, mostly Node's
- own startup. Only Read triggers a hook before the tool runs. `/cco doctor`
- shows the time on your machine.
- **Which models does it know?**
- Opus 5.5, Sonnet 5.5, Haiku 5.5 and Fable 5.1, plus the earlier Claude 5 and
- 4.x models, each with its own window, prices and cache rates. The session's
- real model is read from the transcript; `/cco budget model <name>` sets only
- the fallback.
- **Does the prompt coach call a model?**
- No. It is local heuristics, under 5 ms per prompt, no API calls.
- **Does it work with subagents?**
- Yes. Hooks tell subagents apart by the hook's `agent_id`: each gets its own
- read cache, and its reads never count as the main context's waste.
- **Can read dedup break anything?**
- It only skips a read of the same file, range and context with no change since.
- If Claude repeats the read right after a skip, it goes through, in case its
- copy was cleared.
- **Where did the old "What's new" sections go?**
- To [CHANGELOG.md](CHANGELOG.md), which has every release.
- ---
- ## Support Development
- context-optimizer is **100% free and open source**. No paywalls, no premium tiers, no telemetry. If it saves you money on tokens, consider supporting development:
- | Chain | Address |
- |-------|---------|
- | **BTC** | `bc1q428exz5t2h9rzk7z5ya70madh0j3rs6h4gfgyd` |
- | **ETH (ERC-20)** | `0xB3f0C8e42B7cA9d65920cEfe82e3fef1B5C9d0C9` |
- | **SOL** | `8ctK8nt3CBkPZGfWQXX8TsnqUYUy4JAbT1EMhr8rsQxm` |
- ---
- ## Contributing
- PRs welcome. See [ROADMAP.md](ROADMAP.md) for what's planned and [CONTRIBUTING.md](CONTRIBUTING.md) for how to start. `npm test` runs the suite; `npm run test:engine` runs the meter's tests in Claude Code's own engine.
- ## Credits
- GitHub's [contributors graph](https://github.com/egorfedorov/claude-context-optimizer/graphs/contributors) only counts commits, so the people who found the bugs don't appear in it. They should. Every entry below changed the tool:
- | | Found | Shipped |
- |---|---|---|
- | **[@GesPacClinica](https://github.com/GesPacClinica)** | [#1](https://github.com/egorfedorov/claude-context-optimizer/issues/1) — the very first issue: a clean install on fresh Linux Mint crashed Node on every hook, because `npx skills add` puts `CLAUDE_PLUGIN_ROOT` somewhere with no `src/` | `fd5dc7e` — every hook now tests for the file before running it |
- | **[@zwrose](https://github.com/zwrose)** | [#29](https://github.com/egorfedorov/claude-context-optimizer/pull/29) — `/cco report` crashed outright, and its cost table printed `$NaN` | sent the fix themselves, as a PR |
- | **[@Reapper-Stack](https://github.com/Reapper-Stack)** | [#46](https://github.com/egorfedorov/claude-context-optimizer/issues/46) — on Windows every transcript lookup pointed at a malformed path, so `/cco overhead` always claimed "no transcripts found" — reported with the root cause | v4.7.0 Windows-correct paths |
- | **[@harvest316](https://github.com/harvest316)** | [#53](https://github.com/egorfedorov/claude-context-optimizer/issues/53) — `/cco overhead mcp` told fresh installs to delete MCP servers it had never actually watched; the cold-start guard counted sessions, not evidence — reported with the root cause, the on-disk verification, and the fix | v4.9.1 |
- A report that names the root cause is worth more than one that just names the symptom — #46 and #53 both arrived that way, and #29 arrived as the patch itself.
- Found something? [Open an issue](https://github.com/egorfedorov/claude-context-optimizer/issues/new) — you'll end up on this list.
- ## License
- MIT — do whatever you want with it.
- ---
- <p align="center">
- <sub>Built with frustration at wasted tokens and love for efficiency.</sub><br/>
- <sub>If we saved you money, <a href="#support-development">return the favor</a>.</sub>
- </p>
src/prompt-coach.js · Bundled script · 501 lines
- #!/usr/bin/env node
- /**
- * Prompt Coach v1.0
- *
- * UserPromptSubmit hook + CLI that analyzes the user's prompt for clarity,
- * specificity, and scope — then either:
- * • silently injects context hints into Claude's environment, or
- * • prints suggestions back to the user via stderr so they can refine.
- *
- * Heuristics (model-free):
- * 1. Specificity — does the prompt name files, line numbers, identifiers?
- * 2. Scope — bounded ("fix bug in src/auth.js") vs unbounded
- * ("fix all bugs", "rewrite the codebase")
- * 3. Success — explicit acceptance criteria? tests? expected behaviour?
- * 4. Tech hints — error messages, stack traces, framework names, versions
- * 5. Length — too short (<10 words) is usually under-specified;
- * too long (>500 words) often buries the actual ask
- * 6. Ambiguity — vague verbs (improve, optimise, clean up) without target
- *
- * Output behaviour:
- * • In hook mode (stdin = JSON event): prints additionalContext via JSON
- * output to stdout so Claude sees the coaching suggestions as system info,
- * OR stays silent if the prompt is already strong (score ≥ 80).
- * • In CLI mode (`node prompt-coach.js analyze "..."`): prints a human-
- * readable report to stdout.
- */
- import { readFileSync, existsSync, appendFileSync, readdirSync } from 'fs';
- import { join, basename } from 'path';
- import {
- PROMPTS_DIR, ensureDataDirs, loadJSON, saveJSON,
- estimateTokensFromString, isQuietMode, isMainModule, getThresholds
- } from './utils.js';
- import { recordInjected } from './notices.js';
- ensureDataDirs();
- // ── Heuristic patterns ───────────────────────────────────────────────────────
- const VAGUE_VERBS = [
- 'improve', 'optimize', 'optimise', 'clean up', 'refactor', 'better',
- 'make it nice', 'fix issues', 'fix problems', 'tidy', 'polish',
- // Russian
- 'улучши', 'улучшить', 'оптимизируй', 'оптимизировать', 'почисти',
- 'сделай лучше', 'сделай красиво', 'наведи порядок', 'отрефактори',
- ];
- const STRONG_VERBS = [
- 'add', 'remove', 'rename', 'replace', 'extract', 'inline',
- 'implement', 'create', 'delete', 'fix', 'debug', 'test', 'document',
- // Russian imperatives
- 'добавь', 'удали', 'убери', 'исправь', 'почини', 'поправь', 'сделай',
- 'создай', 'замени', 'переименуй', 'вынеси', 'реализуй', 'напиши',
- 'допиши', 'перепиши', 'настрой', 'обнови', 'проверь', 'протестируй',
- 'запусти', 'разбей', 'найди', 'задеплой', 'релизни', 'закоммить',
- ];
- const UNBOUNDED_PHRASES = [
- /\ball\s+(bugs|files|tests|errors|issues|problems)\b/i,
- /\brewrite\s+(everything|the\s+codebase|all\s+the)/i,
- /\bredesign\s+(everything|the\s+app|the\s+system)/i,
- /\bmake\s+it\s+(nice|better|good|cool|awesome|amazing|perfect)\b/i,
- /\b(improve|optimi[sz]e|fix|refactor|clean\s*up)\s+(everything|all|the\s+(codebase|whole|entire))/i,
- /все\s+(баги|ошибки|файлы|тесты|проблемы)/i,
- /(перепиши|переделай)\s+(вс[её]|весь|всю)/i,
- ];
- const SUCCESS_HINTS = [
- /\btest(s)?\b.*\bpass/i,
- /\bso that\b/i,
- /\bexpected (output|result|behaviour|behavior)/i,
- /\backceptance criteri/i,
- /\bdone when\b/i,
- /\buntil\b/i,
- /\bчтобы\b/i,
- /тест(ы)?\s.*проход/i,
- /должн[оаы]\s/i,
- /ошибк[аи]\s+(исчез|пропа)/i,
- ];
- // ── Language-aware word matching ────────────────────────────────────────────
- // JS \b is ASCII-only: it never fires between a space and a Cyrillic letter,
- // so `\bдобавь\b` silently matches nothing. Cyrillic words use a plain
- // case-insensitive substring check instead (safe for these imperatives).
- const CYRILLIC = /[а-яё]/i;
- function hasWord(text, word) {
- if (CYRILLIC.test(word)) return text.toLowerCase().includes(word);
- return new RegExp(`\\b${word}\\b`, 'i').test(text);
- }
- // ── Conversation classifier ─────────────────────────────────────────────────
- // Not every prompt is a task. Grading "спасибо, всё отлично ))" as F and
- // injecting "name the file you want changed" spends the very tokens the
- // optimizer protects — and erodes trust. Classify first, coach only tasks.
- const ACK_WORDS = [
- // English
- 'ok', 'okay', 'yes', 'no', 'thanks', 'thank', 'cool', 'nice', 'great',
- 'good', 'perfect', 'awesome', 'lgtm', 'sure', 'fine', 'hi', 'hello', 'hey',
- 'continue', 'proceed', 'go', 'stop', 'wait', 'bye',
- // Russian
- 'да', 'нет', 'ок', 'окей', 'спасибо', 'спс', 'отлично', 'круто', 'супер',
- 'хорошо', 'понял', 'поняла', 'ясно', 'ага', 'угу', 'привет', 'давай',
- 'поехали', 'продолжай', 'дальше', 'стоп', 'подожди', 'норм', 'пока',
- ];
- const INTERROGATIVES = [
- // English
- 'why', 'how', 'what', 'who', 'when', 'where', 'which', 'can', 'could',
- 'should', 'is', 'are', 'does', 'do',
- // Russian
- 'почему', 'зачем', 'откуда', 'как', 'что', 'кто', 'где', 'когда',
- 'какой', 'какая', 'какие', 'можно', 'есть',
- ];
- /**
- * Classify a prompt as 'chat' (conversational — don't grade),
- * 'question' (legit question — grade leniently, never inject),
- * or 'task' (a work request — full coaching applies).
- */
- export function classifyPrompt(prompt) {
- const trimmed = (prompt || '').trim();
- if (!trimmed) return 'chat';
- // Strip emoji, emoticons ("))", ":)"), and punctuation for word analysis.
- const cleaned = trimmed
- .replace(/[)(:;=~^]+/g, ' ')
- .replace(/[\p{Emoji_Presentation}\p{Extended_Pictographic}]/gu, ' ')
- .trim();
- const words = cleaned.split(/\s+/).filter(Boolean);
- const hasTaskVerb = STRONG_VERBS.some(v => hasWord(cleaned, v));
- const hasFilePath = FILE_PATH_REGEX.test(cleaned);
- FILE_PATH_REGEX.lastIndex = 0; // global regex — reset between uses
- const hasErrorText = /error|exception|traceback|TypeError|ошибк/i.test(cleaned);
- // Question shape: ends with "?" or opens with an interrogative (optionally
- // after a filler particle like "а" / "so"). Checked before the chat rule so
- // short questions ("how does X work?") aren't dismissed as chit-chat.
- const first = (words[0] || '').toLowerCase().replace(/[.,!?…]+$/, '');
- const second = (words[1] || '').toLowerCase().replace(/[.,!?…]+$/, '');
- const isQuestionShape = /\?\s*$/.test(trimmed) ||
- INTERROGATIVES.includes(first) ||
- (first.length <= 2 && INTERROGATIVES.includes(second));
- if (!hasTaskVerb && isQuestionShape) return 'question';
- // Chat: short, no task verb, no file, no error — acknowledgments, reactions.
- if (!hasTaskVerb && !hasFilePath && !hasErrorText) {
- if (words.length <= 6) return 'chat';
- const lower = words.map(w => w.toLowerCase().replace(/[.,!?…]+$/, ''));
- if (words.length <= 10 && lower.some(w => ACK_WORDS.includes(w))) return 'chat';
- }
- return 'task';
- }
- const TECH_HINTS = [
- /\berror[:\s]/i,
- /\bstack\s*trace\b/i,
- /\bexception\b/i,
- /\bfailed\s+with\b/i,
- /\bcrash(es|ed)?\b/i,
- /Cannot read prop|TypeError|ReferenceError|SyntaxError/,
- /\bv?\d+\.\d+(\.\d+)?\b/, // version numbers
- ];
- // File-path-like substrings: src/foo.ts, tests/bar.spec.js, /Users/.../foo, ./bar.py
- // Allows multi-dot names like foo.spec.js by matching .ext greedily until last segment.
- const FILE_PATH_REGEX = /(?:[a-zA-Z0-9_./-]*\/)?[a-zA-Z0-9_-]+(?:\.[a-zA-Z][a-zA-Z0-9]{0,7})+\b/g;
- const LINE_REF_REGEX = /:\d+(?::\d+)?\b/;
- const IDENTIFIER_REGEX = /\b[a-z][a-zA-Z0-9_]+\(\)|`[^`]+`|\b[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z0-9_]+)+\b/;
- // ── Analyzer ─────────────────────────────────────────────────────────────────
- export function analyzePrompt(prompt) {
- if (!prompt || typeof prompt !== 'string') {
- return { score: 0, grade: 'F', signals: {}, suggestions: ['Empty prompt — write what you want done.'] };
- }
- const trimmed = prompt.trim();
- const words = trimmed.split(/\s+/).filter(Boolean);
- const wordCount = words.length;
- const PC = getThresholds(); // prompt* keys are user-tunable (#39)
- // ── Detect signals ──
- const filePathMatches = (trimmed.match(FILE_PATH_REGEX) || []).filter(s =>
- !s.startsWith('http') && !s.endsWith('.com') && !s.endsWith('.io')
- );
- const hasLineRef = LINE_REF_REGEX.test(trimmed);
- const hasIdentifier = IDENTIFIER_REGEX.test(trimmed);
- const hasSuccess = SUCCESS_HINTS.some(re => re.test(trimmed));
- const hasTechContext = TECH_HINTS.some(re => re.test(trimmed));
- const hasVagueVerb = VAGUE_VERBS.some(v => trimmed.toLowerCase().includes(v));
- const hasStrongVerb = STRONG_VERBS.some(v => hasWord(trimmed, v));
- const hasUnbounded = UNBOUNDED_PHRASES.some(re => re.test(trimmed));
- const hasCodeBlock = /```/.test(trimmed);
- const hasQuestionMark = /\?/.test(trimmed);
- // ── Score components (each 0–100) ──
- const specificity = Math.min(100,
- (filePathMatches.length > 0 ? 35 : 0) +
- (hasLineRef ? 15 : 0) +
- (hasIdentifier ? 25 : 0) +
- (hasCodeBlock ? 25 : 0)
- );
- const scope = Math.min(100,
- (hasUnbounded ? 0 : 50) +
- (hasStrongVerb ? 30 : 0) +
- (hasVagueVerb ? -20 : 0) +
- (wordCount >= PC.promptMinWords && wordCount <= PC.promptIdealMaxWords ? 20 : 0)
- );
- const successCriteria = hasSuccess ? 100 :
- (hasTechContext ? 60 : 30);
- const lengthScore = wordCount < 4 ? 0 :
- wordCount < 10 ? 40 :
- wordCount > PC.promptTooLongWords ? 50 :
- 100;
- // Weighted overall (specificity matters most for prompt quality)
- const score = Math.max(0, Math.round(
- specificity * 0.35 +
- scope * 0.30 +
- successCriteria * 0.20 +
- lengthScore * 0.15
- ));
- let grade;
- if (score >= 90) grade = 'S';
- else if (score >= 80) grade = 'A';
- else if (score >= 65) grade = 'B';
- else if (score >= 50) grade = 'C';
- else if (score >= 35) grade = 'D';
- else grade = 'F';
- // ── Suggestions (concrete, actionable) ──
- const suggestions = [];
- if (specificity < 50 && filePathMatches.length === 0 && !hasIdentifier) {
- suggestions.push('Name the specific file(s), function(s), or module(s) you want changed (e.g. `src/auth/login.ts:42`).');
- }
- if (hasUnbounded) {
- suggestions.push('Bound the scope: instead of "all bugs / rewrite everything", pick one concrete failure or feature.');
- }
- if (hasVagueVerb && !hasStrongVerb) {
- const found = VAGUE_VERBS.find(v => trimmed.toLowerCase().includes(v));
- suggestions.push(`Replace vague "${found}" with a concrete action: add/remove/rename/extract/inline/replace.`);
- }
- if (!hasSuccess && !hasTechContext && wordCount > 8) {
- suggestions.push('State the success condition: what tests pass? what error disappears? what does the new behaviour look like?');
- }
- if (wordCount < 6) {
- suggestions.push('Prompt is very short — Claude will likely re-read many files to guess intent. Add 1–2 sentences of context.');
- }
- if (wordCount > PC.promptTooLongWords) {
- suggestions.push('Prompt is long — the actual ask may be buried. Lead with one sentence stating the goal.');
- }
- if (hasQuestionMark && !hasStrongVerb && wordCount < 30) {
- suggestions.push('Open question without a target — be explicit if you want Claude to plan, implement, or just answer.');
- }
- // Detect inferred file path candidates the user may want to load
- const inferredFiles = [...new Set(filePathMatches)].slice(0, 8);
- return {
- score,
- grade,
- wordCount,
- estTokens: estimateTokensFromString(trimmed),
- signals: {
- specificity, scope, successCriteria, lengthScore,
- filePathsFound: inferredFiles,
- hasLineRef, hasIdentifier, hasSuccess,
- hasTechContext, hasVagueVerb, hasStrongVerb,
- hasUnbounded, hasCodeBlock,
- },
- suggestions,
- };
- }
- /** Build an enhanced version of the user's prompt by appending guardrails. */
- export function buildImprovedPrompt(prompt, analysis) {
- const lines = [prompt.trim()];
- if (analysis.suggestions.length === 0) return prompt;
- lines.push('');
- lines.push('---');
- lines.push('Self-check before answering:');
- if (analysis.signals.specificity < 50) {
- lines.push('- I will identify the exact files/lines I plan to change before editing.');
- }
- if (analysis.signals.scope < 50) {
- lines.push('- I will limit changes to the smallest scope that satisfies the request.');
- }
- if (!analysis.signals.hasSuccess) {
- lines.push('- I will state the success criteria (tests, behaviour, error gone) before declaring done.');
- }
- return lines.join('\n');
- }
- // ── Hook mode ────────────────────────────────────────────────────────────────
- async function readStdin() {
- let input = '';
- for await (const chunk of process.stdin) input += chunk;
- return input;
- }
- function logPrompt(sessionId, prompt, analysis, kind = 'task') {
- try {
- const file = join(PROMPTS_DIR, `${sessionId}.jsonl`);
- const entry = JSON.stringify({
- ts: new Date().toISOString(),
- kind,
- score: analysis.score,
- grade: analysis.grade,
- wordCount: analysis.wordCount,
- signals: analysis.signals,
- suggestions: analysis.suggestions,
- preview: prompt.slice(0, 200),
- }) + '\n';
- // True append: O(1) per prompt and never rewrites (a crash mid-write
- // can't truncate earlier entries, unlike read+concat+write).
- appendFileSync(file, entry);
- } catch { /* best-effort */ }
- }
- /** Count previously logged prompts this session (0 = this is the opener). */
- function priorPromptCount(sessionId) {
- try {
- const file = join(PROMPTS_DIR, `${sessionId}.jsonl`);
- if (!existsSync(file)) return 0;
- return readFileSync(file, 'utf-8').split('\n').filter(Boolean).length;
- } catch { return 0; }
- }
- /**
- * UserPromptSubmit: grade the prompt and, for a weak task prompt, return the
- * coaching text to add to Claude's context ('' = stay silent).
- */
- export function coachPrompt(event) {
- const prompt = event.prompt || '';
- const sessionId = event.session_id || 'unknown';
- // Classify BEFORE grading. Conversational replies and questions are not
- // weak task prompts — coaching them injects noise (and tokens) for nothing.
- const kind = classifyPrompt(prompt);
- if (kind === 'chat') {
- logPrompt(sessionId, prompt, { score: null, grade: '-', wordCount: 0, signals: {}, suggestions: [] }, kind);
- return '';
- }
- const priors = priorPromptCount(sessionId); // before logging this one
- const analysis = analyzePrompt(prompt);
- logPrompt(sessionId, prompt, analysis, kind);
- // Questions get graded for history but never coached — "name the file you
- // want changed" is meaningless advice for "why did X happen?".
- if (kind === 'question') return '';
- // Strong prompt or quiet mode — stay silent.
- if (analysis.score >= 80 || isQuietMode()) return '';
- // Follow-up leniency: mid-conversation, short prompts lean on context that
- // is already loaded. Only coach follow-ups that are truly unbounded.
- if (priors > 0 && analysis.wordCount < 12 && !analysis.signals.hasUnbounded) return '';
- // Weak prompt — inject coaching as additional context (visible to Claude).
- const top = analysis.suggestions.slice(0, 3);
- if (top.length === 0) return '';
- const lines = [
- `[prompt-coach] Prompt quality: ${analysis.grade} (${analysis.score}/100).`,
- 'Suggestions to make this prompt produce better results:',
- ...top.map(s => ` - ${s}`),
- ];
- if (analysis.signals.filePathsFound.length > 0) {
- lines.push(` Inferred files: ${analysis.signals.filePathsFound.join(', ')}`);
- }
- lines.push('');
- lines.push('Apply these mentally before reading files. If the prompt is too vague, ask one clarifying question instead of guessing.');
- const text = lines.join('\n');
- // It enters Claude's context, so it counts against CCO's NET savings.
- recordInjected(sessionId, text);
- return text;
- }
- async function hookMode() {
- const raw = await readStdin();
- if (!raw.trim()) return;
- let event;
- try { event = JSON.parse(raw); } catch { return; }
- if (event.hook_event_name !== 'UserPromptSubmit') return;
- const text = coachPrompt(event);
- if (!text) return;
- console.log(JSON.stringify({
- hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: text },
- }));
- }
- // ── CLI mode ─────────────────────────────────────────────────────────────────
- function cliReport(analysis) {
- const out = [];
- out.push('');
- out.push(` PROMPT QUALITY — ${analysis.grade} (${analysis.score}/100)`);
- out.push(' ' + '─'.repeat(56));
- out.push(` Words: ${analysis.wordCount} Est. tokens: ${analysis.estTokens}`);
- out.push('');
- out.push(' Breakdown:');
- out.push(` Specificity ......... ${String(analysis.signals.specificity).padStart(3)}/100`);
- out.push(` Scope ............... ${String(analysis.signals.scope).padStart(3)}/100`);
- out.push(` Success criteria .... ${String(analysis.signals.successCriteria).padStart(3)}/100`);
- out.push(` Length .............. ${String(analysis.signals.lengthScore).padStart(3)}/100`);
- if (analysis.signals.filePathsFound.length > 0) {
- out.push(` Files mentioned ..... ${analysis.signals.filePathsFound.join(', ')}`);
- }
- if (analysis.suggestions.length > 0) {
- out.push('');
- out.push(' Suggestions:');
- for (const s of analysis.suggestions) out.push(` - ${s}`);
- } else {
- out.push('');
- out.push(' Strong prompt. No suggestions.');
- }
- out.push('');
- return out.join('\n');
- }
- function showHistory(count = 10) {
- if (!existsSync(PROMPTS_DIR)) {
- console.log('No prompt history yet.');
- return;
- }
- const files = readdirSync(PROMPTS_DIR).filter(f => f.endsWith('.jsonl'));
- const all = [];
- for (const f of files) {
- try {
- const lines = readFileSync(join(PROMPTS_DIR, f), 'utf-8').split('\n').filter(Boolean);
- for (const ln of lines) {
- try { all.push(JSON.parse(ln)); } catch { /* skip */ }
- }
- } catch { /* skip */ }
- }
- all.sort((a, b) => new Date(b.ts) - new Date(a.ts));
- const recent = all.slice(0, count);
- console.log(`\n PROMPT HISTORY — last ${recent.length}\n ${'─'.repeat(56)}`);
- for (const e of recent) {
- const ts = e.ts.slice(0, 16).replace('T', ' ');
- const preview = (e.preview || '').replace(/\s+/g, ' ').slice(0, 60);
- console.log(` [${e.grade}] ${ts} ${preview}${preview.length === 60 ? '...' : ''}`);
- }
- if (all.length > 0) {
- const avg = Math.round(all.reduce((s, e) => s + (e.score || 0), 0) / all.length);
- console.log(`\n Average score across ${all.length} prompts: ${avg}/100`);
- }
- console.log('');
- }
- async function main() {
- const action = process.argv[2];
- if (action === 'analyze') {
- const text = process.argv.slice(3).join(' ');
- if (!text) {
- console.error('Usage: node src/prompt-coach.js analyze "<prompt text>"');
- process.exit(1);
- }
- console.log(cliReport(analyzePrompt(text)));
- return;
- }
- if (action === 'history') {
- showHistory(parseInt(process.argv[3], 10) || 10);
- return;
- }
- if (action === 'improve') {
- const text = process.argv.slice(3).join(' ');
- if (!text) {
- console.error('Usage: node src/prompt-coach.js improve "<prompt text>"');
- process.exit(1);
- }
- const a = analyzePrompt(text);
- console.log(buildImprovedPrompt(text, a));
- return;
- }
- // Default: hook mode (read JSON event from stdin)
- await hookMode();
- }
- if (isMainModule(import.meta.url)) main().catch(() => process.exit(0));
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.