when-optimizing-prompts-use-prompt-optimization-analyzer
Active diagnostic tool for analyzing prompt quality, detecting anti-patterns, identifying token waste, and providing optimization recommendations
What this skill does
# Prompt Optimization Analyzer
**Purpose:** Analyze prompt quality and provide actionable optimization recommendations to reduce token waste, improve clarity, and enhance effectiveness.
## When to Use This Skill
- Before publishing new skills or slash commands
- When prompts exceed token budgets
- When responses are inconsistent or unclear
- During skill maintenance and refinement
- When analyzing existing prompt libraries
## Analysis Dimensions
### 1. Token Efficiency Analysis
- Redundancy detection (repeated concepts, phrases)
- Verbosity measurement (word count vs. information density)
- Compression opportunities (equivalent shorter forms)
- Example bloat (excessive or redundant examples)
### 2. Anti-Pattern Detection
- Vague instructions ("do something good")
- Ambiguous terminology (undefined jargon)
- Conflicting requirements (contradictory rules)
- Missing context (insufficient background)
- Over-specification (unnecessary constraints)
### 3. Trigger Issue Analysis
- Unclear activation conditions
- Overlapping trigger patterns
- Missing edge cases
- Too broad/narrow scope
### 4. Structural Optimization
- Information architecture (logical flow)
- Section organization (grouping, hierarchy)
- Reference efficiency (cross-references, links)
- Progressive disclosure (layered detail)
## Execution Process
### Phase 1: Token Waste Detection
```bash
# Analyze prompt for redundancy
npx claude-flow@alpha hooks pre-task --description "Analyzing prompt for token waste"
# Store original metrics
npx claude-flow@alpha memory store --key "optimization/original-tokens" --value "{
\"total_tokens\": <count>,
\"redundancy_score\": <0-100>,
\"verbosity_score\": <0-100>
}"
```
**Analysis Script:**
```javascript
// Embedded token analysis
function analyzeTokenWaste(promptText) {
const metrics = {
totalWords: promptText.split(/\s+/).length,
totalChars: promptText.length,
redundancyScore: 0,
verbosityScore: 0,
issues: []
};
// Detect phrase repetition
const phrases = extractPhrases(promptText, 3); // 3-word phrases
const phraseCounts = countOccurrences(phrases);
const repeated = Object.entries(phraseCounts).filter(([_, count]) => count > 2);
if (repeated.length > 0) {
metrics.redundancyScore += repeated.length * 10;
metrics.issues.push({
type: "redundancy",
severity: "medium",
count: repeated.length,
examples: repeated.slice(0, 3).map(([phrase]) => phrase)
});
}
// Measure verbosity
const avgWordLength = promptText.split(/\s+/)
.reduce((sum, word) => sum + word.length, 0) / metrics.totalWords;
if (avgWordLength > 6) {
metrics.verbosityScore += 20;
metrics.issues.push({
type: "verbosity",
severity: "low",
avgWordLength: avgWordLength.toFixed(2),
suggestion: "Consider shorter, clearer words"
});
}
// Detect filler words
const fillerWords = ["very", "really", "just", "actually", "basically", "simply"];
const fillerCount = fillerWords.reduce((count, filler) => {
const regex = new RegExp(`\\b${filler}\\b`, 'gi');
return count + (promptText.match(regex) || []).length;
}, 0);
if (fillerCount > 5) {
metrics.redundancyScore += fillerCount * 2;
metrics.issues.push({
type: "filler-words",
severity: "low",
count: fillerCount,
suggestion: "Remove unnecessary filler words"
});
}
return metrics;
}
function extractPhrases(text, wordCount) {
const words = text.toLowerCase().split(/\s+/);
const phrases = [];
for (let i = 0; i <= words.length - wordCount; i++) {
phrases.push(words.slice(i, i + wordCount).join(' '));
}
return phrases;
}
function countOccurrences(items) {
return items.reduce((counts, item) => {
counts[item] = (counts[item] || 0) + 1;
return counts;
}, {});
}
```
### Phase 2: Anti-Pattern Detection
**Common Anti-Patterns:**
1. **Vague Instructions**
- ❌ "Make it better"
- ✅ "Reduce token count by 20% while maintaining clarity"
2. **Ambiguous Terminology**
- ❌ "Handle errors appropriately"
- ✅ "Catch exceptions, log to memory, return user-friendly message"
3. **Conflicting Requirements**
- ❌ "Be concise but provide detailed explanations"
- ✅ "Provide concise summaries with optional detail links"
4. **Missing Context**
- ❌ "Use the standard format"
- ✅ "Use JSON format: {type, severity, description}"
5. **Over-Specification**
- ❌ "Always use exactly 4 spaces, never tabs, indent 2 levels..."
- ✅ "Follow project .editorconfig settings"
**Detection Script:**
```javascript
function detectAntiPatterns(promptText) {
const patterns = [];
// Vague instruction markers
const vagueMarkers = ["better", "good", "appropriate", "proper", "suitable"];
vagueMarkers.forEach(marker => {
if (new RegExp(`\\b${marker}\\b`, 'i').test(promptText)) {
patterns.push({
type: "vague-instruction",
marker: marker,
severity: "high",
suggestion: "Replace with specific, measurable criteria"
});
}
});
// Missing definitions
const technicalTerms = promptText.match(/\b[A-Z][A-Za-z]*(?:[A-Z][a-z]*)+\b/g) || [];
const definedTerms = (promptText.match(/\*\*[^*]+\*\*:/g) || []).length;
if (technicalTerms.length > 5 && definedTerms < technicalTerms.length * 0.3) {
patterns.push({
type: "undefined-jargon",
severity: "medium",
technicalTermCount: technicalTerms.length,
definedCount: definedTerms,
suggestion: "Add definitions for technical terms"
});
}
// Conflicting modal verbs
const mustStatements = (promptText.match(/\b(must|required|mandatory)\b/gi) || []).length;
const shouldStatements = (promptText.match(/\b(should|recommended|optional)\b/gi) || []).length;
if (mustStatements > 10 && shouldStatements > 10) {
patterns.push({
type: "requirement-confusion",
severity: "medium",
mustCount: mustStatements,
shouldCount: shouldStatements,
suggestion: "Separate MUST vs SHOULD requirements clearly"
});
}
return patterns;
}
```
### Phase 3: Trigger Analysis
```javascript
function analyzeTriggers(triggerText) {
const issues = [];
// Check clarity
if (!triggerText.includes("when") && !triggerText.includes("if")) {
issues.push({
type: "unclear-condition",
severity: "high",
suggestion: "Use explicit 'when' or 'if' conditions"
});
}
// Check specificity
const vagueTerms = ["thing", "stuff", "something", "anything"];
vagueTerms.forEach(term => {
if (new RegExp(`\\b${term}\\b`, 'i').test(triggerText)) {
issues.push({
type: "vague-trigger",
term: term,
severity: "high",
suggestion: "Replace with specific entity or action"
});
}
});
// Check scope
if (triggerText.split(/\s+/).length < 5) {
issues.push({
type: "too-narrow",
severity: "medium",
wordCount: triggerText.split(/\s+/).length,
suggestion: "Consider broader applicability"
});
}
return issues;
}
```
### Phase 4: Optimization Recommendations
**Code Analyzer Agent Task:**
```bash
# Spawn analyzer agent
# Agent instructions:
# 1. Analyze prompt structure and flow
# 2. Identify optimization opportunities
# 3. Generate before/after comparisons
# 4. Calculate token savings
# 5. Store recommendations in memory
npx claude-flow@alpha memory store --key "optimization/recommendations" --value "{
\"structural\": [...],
\"content\": [...],
\"examples\": [...],
\"estimated_savings\": \"X tokens (Y%)\"
}"
```
### Phase 5: Before/After Comparison
**Optimization Report Format:**
```markdown
## Prompt Optimization Report
### Original Metrics
- Total tokens: <count>
- Redundancy score: <0-100>
- Verbosity score: <0-100>
- Anti-patterns found: <count>
### Issues Detected
#### High Severity
1. [Type] <description>
- Location: <section>
- Impact: <token/clarity impact>
- Fix: <recommendation>
#### Medium Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.