
Accelint Prompt Manager
- 120 installs
- 21 repo stars
- Updated August 4, 2026
- gohypergiant/agent-skills
accelint-prompt-manager is a Claude skill that rewrites vague requests into validated prompts so developers can execute work with explicit goals and success criteria.
About
accelint-prompt-manager refines underspecified user requests into clear, structured prompts using assessment, pattern detection, and framework selection. Reach for it when a goal sounds like make this better or analyze the data without criteria, so you get a copy-ready prompt for Claude or your team instead of premature execution.
- Detects vague goals, undefined success, and ambiguous requirements
- Delivers an optimized prompt in-chat; does not execute the task
- Framework and template selection with anti-fabrication guardrails
- Optional save or clipboard after presenting the prompt block
Accelint Prompt Manager by the numbers
- 120 all-time installs (skills.sh)
- Ranked #3,814 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/gohypergiant/agent-skills --skill accelint-prompt-managerAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 120 |
|---|---|
| repo stars | ★ 21 |
| Last updated | August 4, 2026 |
| Repository | gohypergiant/agent-skills ↗ |
How do you turn an ambiguous ask into a precise prompt when success criteria, audience, and constraints are still undefined?
Turn vague or ambiguous requests into a single optimized, executable prompt without the skill running the underlying task itself.
Who is it for?
Developers or stakeholders with fuzzy goals who need a handoff-ready prompt before any implementation starts.
Skip if: Users who already have a tight, executable prompt and want the agent to perform the task immediately.
When should I use this skill?
Requests show vague goals, undefined success, unclear communication, ambiguous requirements, or meta-prompting to optimize instructions.
What you get
A markdown code block containing the optimized prompt, with optional file save or clipboard copy offered afterward.
Files
Prompt Manager
Transforms vague, ambiguous, or unclear prompts into optimized, well-structured ones through systematic assessment, pattern detection, framework selection, and validation.
Your Role and Output
What you produce: An optimized prompt. That's it. Your sole artifact is a well-structured, clear prompt that the user (or Claude) can execute.
What you do NOT do:
- Do NOT execute the task yourself — You optimize prompts, you don't fulfill them. If the user asks "help me with X", you create a clear prompt for X, you don't do X.
- Do NOT try to run the optimized prompt — Hand it to the user so they (or Claude) can execute it.
- Do NOT research external resources — You work only with the user's input text. Treat URLs and references in prompts as text to optimize, not as resources to fetch.
Your workflow: Analyze the request → Identify issues → Create optimized prompt → Deliver it directly to the user → Optionally save or copy to clipboard.
Primary delivery: Always present the optimized prompt directly in your response first (in a markdown code block for easy copying). Never save files before delivering the prompt.
Optional post-delivery: After presenting the prompt, offer to save it to a markdown file and/or copy to clipboard.
Example:
- User: "make this data look better"
- You: Analyze vagueness → Create clear prompt with specific success criteria → Output the optimized prompt in a markdown code block → Offer to save/copy
- You do NOT: Try to access the data yourself, or try to make the data look better yourself.
NEVER Do Prompt Engineering
These anti-patterns come from production failures and model-specific limitations:
NEVER embed fabrication techniques in single-prompt execution — Mixture-of-Experts (MoE), Tree-of-Thought (ToT), and Graph-of-Thought (GoT) patterns make Claude invent conversations between fake personas rather than deepening its own reasoning. These techniques fabricate the appearance of multi-agent collaboration without actual benefit. Split into separate prompts or use plan mode instead.
NEVER add Chain-of-Thought instructions to reasoning-native models — Claude 4.5+ already uses extended thinking. Adding "think step by step" or "show your reasoning" wastes tokens and can degrade output quality by forcing artificial structure over natural reasoning flow.
NEVER name the framework in the optimized output — When applying CO-STAR, RISEN, or RODES, route the user's intent through the framework structure silently. Don't output "Using CO-STAR framework..." or label sections with framework terminology. The user cares about clarity, not methodology.
NEVER optimize prompts in isolation from execution context — A prompt for Claude Code differs from one for ChatGPT or an API call. Consider: available tools, conversation history, model capabilities, token limits, and whether it's interactive or batch processing. Context determines optimization strategy.
NEVER use vague success criteria — "Make this better", "comprehensive documentation", "clean code" lack objective validation. Pin criteria to measurable outcomes: test coverage percentage, specific edge cases handled, response time constraints, or concrete examples of acceptable output.
NEVER skip constraint specification for creative tasks — Without boundaries, creative prompts produce wildly inconsistent results. Specify: tone, length, style references, what to avoid, audience expectations, and format requirements. Constraints enable creativity by defining the solution space.
NEVER front-load all context in long prompts — The "lost-in-the-middle" problem causes models to weaken attention on middle sections of very long prompts. Place critical instructions at the beginning and end. Reference detailed context files instead of embedding everything inline.
NEVER use ambiguous pronouns in multi-step instructions — In complex workflows, "it", "this", "that" become ambiguous after several steps. Use specific nouns: "the API response", "the user input", "the validated data". Ambiguity compounds across steps, causing execution drift.
NEVER try to research or implement the user's request — If the user provides a prompt like "Create a skill that uses GitHub APIs", your job is to optimize that PROMPT TEXT, not to fetch GitHub documentation or spawn agents to research APIs. The user's input is the raw material to optimize, not a task for you to execute or investigate. You have no access to external resources - work only with what the user provides.
Before Optimizing a Prompt, Ask
These questions reveal optimization opportunities and prevent misaligned refinements:
Task Type Assessment
- Is this objective (testable, deterministic) or subjective (taste, judgment)?
- What's the consequence of failure? (Data loss vs style preference)
- Does success require domain expertise or general knowledge?
Complexity Detection
- Can this be completed in a single pass or does it require planning?
- How many unspecified variables exist? (Who's the audience? What's "good enough"?)
- Are there interdependent decisions that affect each other?
- How many sequential phases does execution require?
Context Calibration
- Who will execute this? (Model type, skill level, available tools)
- Where will this run? (Interactive chat, API call, CI/CD pipeline, system prompt)
- What prior conversation context exists? (Cold start vs continuation)
Framework Selection
- Does the task need structured output? → CO-STAR (format-driven)
- Does the task involve multi-step procedure? → RISEN (process-driven)
- Does the task require examples for clarity? → RODES (example-driven)
Ambiguity Identification
- Which terms have multiple interpretations? ("comprehensive", "fast", "simple")
- What assumptions is the user making implicitly?
- What's the impact of choosing interpretation A vs B?
How to Use
Start with the 4-phase workflow in this file. When you detect specific patterns or need detailed examples, load references on-demand:
- Credit-killing patterns detected? → Load
references/credit-killing-patterns.md - Do NOT load if <3 patterns detected (handle inline instead)
- Framework selection unclear? → Load
references/frameworks.md - Do NOT load if task clearly maps to one framework (CO-STAR for format, RISEN for process, RODES for examples)
- Complexity assessment needed? → Load
references/complexity-detection.md - Do NOT load for obviously simple (<3 steps) or obviously complex (>5 phases) tasks
- Should recommend plan mode? → Load
references/plan-mode-triggers.md - Do NOT load if user explicitly declined plan mode
- Ambiguity examples needed? → Load
references/ambiguity-examples.md - Do NOT load if ambiguities are straightforward (can resolve without examples)
- Safe techniques for optimization? → Load
references/safe-techniques.md - Do NOT load for experienced users who understand optimization principles
- Template selection logic? → Load
references/template-selection.md - Do NOT load if not using templates or task type is obvious
- Before/after examples needed? → Load
references/optimization-examples.md - Do NOT load for expert users or when delivering final optimized prompt
Quick reference summary available in AGENTS.md.
Prompt Optimization Workflow
Use this progress checklist to track optimization:
- [ ] Phase 1: Intake & Assessment
- [ ] Phase 2: Pattern Detection
- [ ] Phase 3: Framework Selection & Optimization
- [ ] Phase 4: Validation & HandoffStep 0: Verify Intent (Gate Question)
Before starting, confirm the user's intent:
Ask: "I specialize in optimizing prompts to make them clearer and more actionable. Is that what you need, or did you want me to help with the task itself?"
If user wants prompt optimization: Proceed with Phase 1.
If user wants task execution: "I only optimize prompts—I don't execute the tasks they describe. Please exit this skill and I'll help you with the task itself."
Skip this gate question when:
- User explicitly requests prompt optimization ("optimize this prompt", "improve my prompt", "make this clearer")
- User provides prompt in quotes/code blocks with meta-instructions
- Context clearly indicates prompt optimization (discussing frameworks, asking about CO-STAR/RISEN/RODES)
Phase 1: Intake & Assessment
Goal: Understand user intent, skill level, task complexity, and execution context.
Actions: 1. Extract Core Intent — Identify the underlying goal from the request. 2. Assess User Skill Level — Infer from language and terminology:
- Newcomer: Vague terms, needs guidance, unfamiliar with frameworks
- Intermediate: Understands basics, may skip details, knows some patterns
- Expert: Precise terminology, assumes context, references specific techniques
3. Detect Task Complexity — Count decision points, dependencies, phases:
- Simple: Single clear objective, <3 steps, no ambiguity
- Moderate: Some ambiguity, 3-5 steps, few dependencies
- Complex: >3 interdependent decisions OR >5 sequential phases
4. Identify Execution Context — Where and how will this run?
- Interactive conversation vs batch API call
- Model type and capabilities
- Available tools and integrations
- Token budget constraints
For Complex Tasks: Recommend plan mode before proceeding. Explain: "This task involves [X dependencies and Y phases]. Plan mode will help design the approach before execution, preventing rework."
Skip Conditions: If user explicitly declines plan mode recommendation, continue with note about complexity.
Output: Clear understanding of intent, user calibration, complexity level, execution context.
Phase 2: Pattern Detection
Goal: Identify credit-killing patterns, ambiguities, and trade-offs that undermine prompt effectiveness.
Actions: 1. Scan for Credit-Killing Patterns — Check against common anti-patterns:
- Fabrication techniques (MoE, ToT, GoT)
- Inappropriate CoT instructions
- Framework name pollution
- Context-free optimization
- Vague success criteria
- Missing constraints for creative tasks
- Front-loaded long context
- Ambiguous pronouns in steps
If 3+ patterns detected, load references/credit-killing-patterns.md for full catalog.
2. Flag Ambiguities — List terms/constraints with multiple interpretations:
- "Comprehensive" — All edge cases [+time] vs common scenarios [balanced] vs overview [+speed]?
- "Fast" — Response time, development time, or execution time?
- "Simple" — Minimal code, easy to understand, or few dependencies?
For each ambiguity, provide 2-3 interpretation options with implications.
3. Identify Trade-Offs — Expose competing goals:
- Speed vs thoroughness
- Flexibility vs consistency
- Creativity vs structure
- Token efficiency vs clarity
Present trade-offs explicitly; never assume user preference.
4. Assess Missing Context — What critical information is absent?
- Target audience undefined
- Success criteria unspecified
- Constraints missing
- Format requirements unclear
For Newcomers: Explain what's being detected and why it matters. For Experts: Cite pattern names and line numbers directly.
Output: Categorized list of issues (patterns, ambiguities, trade-offs, missing context) with severity levels.
Phase 3: Framework Selection & Optimization
Goal: Apply appropriate framework (CO-STAR, RISEN, RODES) and safe optimization techniques to create clear, actionable prompt.
Actions: 1. Select Framework — Choose based on task type:
- CO-STAR: Structured output, specific format needs → Format-driven
- RISEN: Multi-step procedures, workflows → Process-driven
- RODES: Needs examples for clarity, style matching → Example-driven
Load references/frameworks.md if selection is unclear.
2. Apply Framework Silently — Route user intent through framework structure WITHOUT naming it:
- Extract: Context, Objective, Style, Tone, Audience, Response format (CO-STAR)
- Extract: Role, Instructions, Steps, End goal, Narrowing (RISEN)
- Extract: Role, Objective, Details, Examples, Sense check (RODES)
3. Apply Safe Techniques — Use proven optimization methods:
- Specificity injection: Replace vague terms with concrete criteria
- Constraint addition: Define boundaries for creative freedom
- Context positioning: Critical info at start/end, not middle
- Pronoun elimination: Replace "it/this/that" with specific nouns
- Success criteria definition: Pin to measurable outcomes
Load references/safe-techniques.md for detailed explanations.
4. Address Flagged Issues — Resolve each item from Phase 2:
- Remove credit-killing patterns
- Disambiguate vague terms
- Specify constraints
- Add missing context
- Clarify trade-off choices
5. Format for Execution Context — Adapt to where this will run:
- Interactive: Conversational tone, progressive disclosure
- API/batch: Complete context, no assumptions of follow-up
- System prompt: Permanent guidelines, avoid temporal references
- Tool integration: Structured format, clear input/output specs
Output: Optimized prompt that addresses all detected issues, applies appropriate framework structure, and matches execution context.
Phase 4: Validation & Handoff
Goal: Quality-check optimized prompt and provide clear next steps.
Actions: 1. Run Quality Checks:
- ✓ All ambiguities resolved or flagged for user decision
- ✓ Success criteria are concrete and measurable
- ✓ Constraints are specified where needed
- ✓ Context is positioned appropriately (not lost-in-middle)
- ✓ Pronouns are specific in multi-step instructions
- ✓ No fabrication techniques in single-prompt execution
- ✓ Framework applied silently (no methodology exposed)
2. Flag Remaining Ambiguities — If user decisions needed:
- Present options with clear implications
- Explain trade-offs
- Recommend default if applicable
- Get user confirmation before proceeding
3. Recommend Execution Mode:
- Simple tasks: Execute directly with optimized prompt
- Moderate tasks: Proceed with execution, monitor for issues
- Complex tasks: Use plan mode (if not already recommended)
4. Deliver Optimized Prompt Directly:
- For newcomers: Show before/after comparison, explain key changes
- For experts: Deliver optimized version with concise optimization notes
- CRITICAL: Always present the optimized prompt in a markdown code block first. This ensures easy copying and prevents workflow blockage.
- Use triple backticks with
markdownlanguage identifier for clean formatting
5. Offer Post-Delivery Options: After delivering the optimized prompt, offer:
- "Would you like me to save this to a markdown file?"
- "Should I copy this to your clipboard?"
- "Or both?"
How to handle each:
- Save to file: Ask where to save (suggest:
./prompts/optimized-prompt-YYYY-MM-DD.mdor user's preferred location), then use Write tool - Copy to clipboard: Use Bash tool with OS-appropriate command:
- macOS:
echo "prompt text" | pbcopy - Linux:
echo "prompt text" | xclip -selection clipboard(orxsel) - Windows:
echo "prompt text" | clip - Both: Execute save then clipboard in sequence
For refinements: When user asks to refine the prompt, deliver the refined version and repeat these post-delivery options.
6. Offer to Iterate:
- "Would you like me to refine any specific aspect of this prompt?"
- "Should I adjust the optimization for a different execution context?"
- "Do you want to see alternative approaches to structuring this prompt?"
NEVER offer to execute the task. Your job is prompt optimization + optional save/copy.
Output: Validated, executable prompt delivered directly in your response + clear next steps.
Freedom Calibration
How closely to follow vs adapt these guidelines:
| Task Fragility | Freedom Level | Guidance |
|---|---|---|
| Meta-prompts / System prompts | Low | Follow framework structures exactly — these define behavior for other prompts |
| Prompt optimization for production | Medium | Apply frameworks with examples — balance consistency with context-specific needs |
| Creative prompt design | High | Use principles and anti-patterns as guardrails — adapt freely to user's creative vision |
Higher fragility (left) = stricter adherence. Lower fragility (right) = more adaptation freedom.
Important Notes
Model-Specific Behavior Differs Significantly Claude 4.5+ uses extended thinking natively, GPT-4 uses internal CoT, older models benefit from explicit CoT instructions. Optimization strategies that work for one model family may degrade performance in another. Always consider target model capabilities.
Memory Blocks Prevent Contradictions In extended conversations, save optimization patterns to memory blocks so future prompts don't contradict established guidelines. Without memory persistence, each optimization starts from scratch and may conflict with previous work.
Token Economy Matters in Production Every word in a system prompt multiplies by number of API calls. Verbose instructions become expensive at scale. Balance clarity with conciseness. Progressive disclosure (load detail on-demand) reduces base token cost.
Security Implications of Prompt Injection When optimizing prompts that handle user input, consider injection attacks. Validate and sanitize inputs, use delimiters to separate instructions from data, and never allow user content to override system instructions.
Prompt Manager — Quick Reference
Expert-only knowledge for transforming vague prompts into optimized, actionable ones. This guide focuses on non-obvious patterns, hard-won insights, and systematic optimization techniques.
How to Use This Guide
1. Start with SKILL.md — Run the 4-phase workflow for any prompt optimization 2. Reference this guide — Quick lookup for patterns, frameworks, and techniques 3. Load details on-demand — Deep-dive into specific references/ files as needed
Quick Reference
Anti-Patterns (NEVER Do)
Fabrication Techniques — MoE/ToT/GoT make Claude invent fake personas instead of deepening reasoning → references/credit-killing-patterns.md#fabrication
CoT on Reasoning Models — Claude 4.5+ has native extended thinking, adding "think step-by-step" degrades quality → references/credit-killing-patterns.md#cot
Framework Name Pollution — Never output "Using CO-STAR..." or label sections with methodology → references/credit-killing-patterns.md#naming
Context-Free Optimization — Prompts for Claude Code differ from ChatGPT/API calls, context determines strategy → references/credit-killing-patterns.md#context
Vague Success Criteria — "Better", "comprehensive", "clean" lack measurability, pin to objective outcomes → references/credit-killing-patterns.md#criteria
Missing Creative Constraints — Without boundaries, creative tasks produce inconsistent results → references/credit-killing-patterns.md#constraints
Lost-in-the-Middle — Models weaken attention on middle sections of long prompts, place critical info at start/end → references/credit-killing-patterns.md#context-positioning
Ambiguous Pronouns — "It/this/that" become unclear in multi-step workflows, use specific nouns → references/credit-killing-patterns.md#pronouns
Frameworks
When to Use Which:
- CO-STAR → Structured output, specific format needs (format-driven)
- RISEN → Multi-step procedures, workflows (process-driven)
- RODES → Needs examples for clarity, style matching (example-driven)
Application Rule: Route user intent through framework structure silently — never expose methodology in output
→ Full details: references/frameworks.md
Optimization Techniques
5 Safe Techniques that improve prompt quality without risk: 1. Specificity Injection — Replace vague terms with concrete criteria 2. Constraint Addition — Define boundaries for creative freedom 3. Context Positioning — Critical info at start/end, not middle 4. Pronoun Elimination — Replace "it/this/that" with specific nouns 5. Success Criteria Definition — Pin to measurable outcomes
→ Detailed examples: references/safe-techniques.md
Complexity Assessment
Simple: Single objective, <3 steps, no ambiguity → Execute directly Moderate: Some ambiguity, 3-5 steps, few dependencies → Proceed with monitoring Complex: >3 interdependent decisions OR >5 sequential phases → Recommend plan mode
→ Full criteria: references/complexity-detection.md
Plan Mode Triggers
Always recommend plan mode when:
- >3 interdependent decisions that affect each other
- >5 sequential phases requiring coordination
- Significant ambiguity with cascading implications
- User asks "how should I approach this?"
→ Detailed triggers: references/plan-mode-triggers.md
Ambiguity Patterns
Common Vague Terms:
- "Comprehensive" → All edge cases [+time] vs common scenarios [balanced] vs overview [+speed]
- "Fast" → Response time, development time, or execution time?
- "Simple" → Minimal code, easy to understand, or few dependencies?
- "Clean" → Follows standards, minimal complexity, or well-documented?
Resolution Pattern: Present 2-3 interpretation options with implications, let user decide
→ Full catalog: references/ambiguity-examples.md
Template Selection
12 Task-Type Templates:
- Analytical — Data analysis, metrics, research
- Creative — Writing, design, ideation
- Debugging — Error investigation, root cause analysis
- Documentation — README, API docs, guides
- Exploration — Codebase discovery, pattern finding
- Implementation — Feature building, coding
- Planning — Architecture, approach design
- Refactoring — Code improvement, restructuring
- Review — Code review, quality assessment
- Security — Vulnerability analysis, threat modeling
- Testing — Test writing, QA, validation
- Troubleshooting — System issues, incident response
→ Selection logic: references/template-selection.md → Full templates: assets/prompt-templates/
Optimization Examples
Before/After Transformations:
- Vague request → Specific, constrained prompt
- Ambiguous multi-step → Clear sequential workflow
- Missing context → Fully specified execution environment
- Generic goal → Measurable success criteria
→ Full examples: references/optimization-examples.md
Workflow Summary
Phase 1: Intake & Assessment
↓ Extract intent, calibrate skill level, detect complexity
Phase 2: Pattern Detection
↓ Identify credit-killing patterns, ambiguities, trade-offs
Phase 3: Framework Selection & Optimization
↓ Apply CO-STAR/RISEN/RODES silently, use safe techniques
Phase 4: Validation & Handoff
↓ Quality checks, flag remaining ambiguities, recommend execution modeImportant Context
Model-Specific: Claude 4.5+ uses native extended thinking, GPT-4 uses internal CoT — optimization strategies differ by model family
Token Economy: System prompts multiply by API call count — progressive disclosure reduces base cost
Security: Validate user inputs, use delimiters, never allow user content to override system instructions
Memory Persistence: Save optimization patterns to memory blocks to prevent contradictions in extended conversations
Analytical Template
Use for: Data analysis, metrics interpretation, research synthesis, pattern finding.
Structure
Analyze [DATA_SOURCE] to answer: [SPECIFIC_QUESTIONS]
Data format: [STRUCTURE_DESCRIPTION]
Analysis methods: [STATISTICAL_TECHNIQUES_IF_APPLICABLE]
Context:
- [Background information]
- [Why this analysis matters]
- [What decisions depend on findings]
Output format:
1. Executive summary (key findings in 2-3 sentences)
2. Detailed analysis
- Finding 1: [Evidence + reasoning]
- Finding 2: [Evidence + reasoning]
- Finding 3: [Evidence + reasoning]
3. Recommendations (actionable next steps)
4. Limitations/caveats (what this analysis can't tell us)
Success criteria:
✓ [Measurable validation criterion 1]
✓ [Measurable validation criterion 2]Example Usage
Analyze user engagement metrics from last quarter to identify factors driving retention.
Data format:
- Source: analytics.csv (50k rows)
- Columns: user_id, signup_date, last_active, feature_usage, subscription_tier
- Time period: Q4 2025 (Oct-Dec)
Analysis methods:
- Cohort analysis by signup month
- Correlation analysis between feature usage and retention
- Segment comparison (free vs paid users)
Context:
- Retention dropped from 75% to 68% last quarter
- Product team needs to prioritize features for Q1
- Decision: Which features to invest in for retention improvement
Output format:
1. Executive summary
- Key finding: Power users of feature X have 2.3x higher retention
2. Detailed analysis
- Finding 1: Feature X usage correlates strongest with retention (r=0.67)
- Finding 2: Users who engage in first week have 3x higher 90-day retention
- Finding 3: Free-to-paid conversion happens most at day 14 (spike in data)
3. Recommendations
- Prioritize onboarding flow to drive feature X adoption in first week
- Add day-14 upgrade prompt (catches conversion spike timing)
- Investigate why feature X drives retention (qualitative research)
4. Limitations
- Correlation ≠ causation (need A/B test to confirm causal relationship)
- Data doesn't include customer support interactions
- Small sample size for enterprise tier (only 200 users)
Success criteria:
✓ Analysis identifies top 3 retention drivers with statistical confidence
✓ Recommendations are actionable and prioritized by expected impact
✓ Limitations clearly stated to prevent over-confident decisionsCommon Pitfalls
- Vague questions: "Analyze user behavior" → Specify: "Which features correlate with retention?"
- Missing context: Don't know why analysis matters → Can't prioritize findings appropriately
- No validation criteria: How do you know analysis is complete and correct?
- Ignoring limitations: Every analysis has blind spots, state them explicitly
Creative Template
Use for: Writing, design, ideation, naming, marketing copy, storytelling.
Structure
Create [CREATIVE_ARTIFACT] for [TARGET_AUDIENCE]
Context:
- Purpose: [Why this exists, what it accomplishes]
- Background: [Relevant context that informs creative direction]
Tone/Style: [DESIRED_FEEL]
Must include:
- [Required element 1]
- [Required element 2]
- [Required element 3]
Avoid:
- [Things that don't fit brand/purpose]
- [Overused patterns to skip]
Examples of desired style:
[2-3 concrete examples showing the pattern you want to match]
Constraints:
- Length: [word count or time/size limits]
- Format: [structure requirements]
- Brand guidelines: [specific rules if applicable]
Success criteria:
- [Subjective criterion 1]: measured by [how to evaluate]
- [Subjective criterion 2]: measured by [how to evaluate]Example Usage
Create a product announcement blog post for our new caching feature, targeting technical decision-makers.
Context:
- Purpose: Announce feature launch, drive trial signups
- Background: Customers have been requesting caching for months
- Launching next week, need post ready for launch day
Tone/Style: Professional but approachable. Confident without being salesy. Technical enough to be credible, but accessible to non-engineers.
Must include:
- Clear problem statement (why caching matters)
- 2-3 specific customer benefits with metrics
- How it works (high-level, not implementation details)
- Call-to-action to try it
Avoid:
- Marketing buzzwords ("revolutionary", "game-changing", "cutting-edge")
- Technical jargon without explanation
- Feature list without benefits
- Hype without substance
Examples of desired style:
Example 1 (Vercel's announcement):
"Next.js 13 introduces a new data fetching system that makes pages faster by default. Instead of waiting for all data to load, pages can now stream content as it becomes available. This means users see content 40% faster in our benchmarks."
Example 2 (Stripe's blog):
"When you're processing payments at scale, every millisecond matters. Our new Edge API reduces latency by routing requests to the nearest data center. Early customers see 65ms average response times—down from 180ms."
Constraints:
- Length: 500-700 words
- Format: Markdown with 2-3 sections (Problem, Solution, How It Works, Get Started)
- Brand: Match our existing blog tone (see recent posts at blog.example.com)
Success criteria:
- Clearly communicates value to technical audience (validated by internal eng review)
- Drives curiosity to try the feature (includes compelling CTAs)
- Builds credibility with specific metrics and technical accuracyCommon Pitfalls
- No audience definition: "Write a post" → For whom? Changes everything.
- Missing constraints: Unlimited freedom produces inconsistent results
- No examples: "Professional tone" means different things to different people
- Vague success: "Good writing" → Define what "good" means for this context
Debugging Template
Use for: Error investigation, bug fixing, root cause analysis, troubleshooting.
Structure
Debug this issue: [SYMPTOM_DESCRIPTION]
Expected behavior: [What should happen]
Actual behavior: [What's happening instead]
Error messages:
[Paste exact error text, stack traces, or relevant log lines]
Environment:
- [Language/framework versions]
- [Operating system]
- [Relevant configuration]
- [Recent changes that might be related]
Steps to reproduce:
1. [Action 1]
2. [Action 2]
3. [Observe: actual behavior]
Already tried:
- [Attempt 1]: [Result]
- [Attempt 2]: [Result]
Investigation approach:
1. Reproduce the issue reliably
2. Isolate the root cause (narrow down to specific code/config)
3. Form hypothesis about why it's failing
4. Test hypothesis with targeted changes
5. Implement fix with rationale
6. Verify fix resolves issue without introducing regressions
Success criteria:
✓ Root cause identified and understood
✓ Fix resolves issue in all reproduction cases
✓ No regressions (existing functionality still works)
✓ Add test case to prevent future regressionExample Usage
Debug login failure occurring only on mobile browsers.
Expected behavior:
- User enters valid credentials
- Clicks "Login" button
- Redirected to dashboard with authenticated session
Actual behavior:
- User enters valid credentials
- Clicks "Login" button
- Loading spinner shows briefly
- Login fails silently (no error message)
- User remains on login screen
Error messages:
[Browser console, iOS Safari]
"SecurityError: The operation is insecure."
at saveAuthToken (auth.js:42)
[No server-side errors logged]
Environment:
- Frontend: React 18, running on Vite 4
- Occurs on: iOS Safari 16+, Android Chrome 110+
- Does NOT occur on: Desktop browsers (any)
- Started: After deployment on 2024-03-15
- Affects: ~15% of mobile users
Steps to reproduce:
1. Open site on iPhone Safari
2. Navigate to /login
3. Enter credentials: test@example.com / password123
4. Tap "Login" button
5. Observe: login fails silently, console shows SecurityError
Already tried:
- Verified API returns 200 OK with valid token: ✓ Works correctly
- Checked CORS headers: ✓ Properly configured
- Tested on desktop: ✓ Works fine
- Rolled back recent frontend changes: ✗ Issue persists
Investigation approach:
1. Reproduce issue in mobile browser dev tools
2. Identify exact line causing SecurityError (auth.js:42)
3. Research SecurityError in mobile browser context
→ Hypothesis: localStorage access restricted in iOS Safari private mode or cross-origin iframe
4. Check if we're saving to localStorage vs cookies
→ Finding: Using localStorage.setItem('authToken', token)
5. Test: Switch from localStorage to httpOnly cookies
6. Verify: Login works on mobile after cookie-based auth
Root cause: iOS Safari blocks localStorage in certain contexts (cross-origin iframes, private browsing). Desktop browsers more permissive.
Fix: Replace localStorage with httpOnly cookies for auth tokens
- More secure anyway (XSS protection)
- Works across all browsers and modes
- Server-side change needed: set cookie on login response
Success criteria:
✓ Mobile users can log in successfully
✓ Desktop users unaffected (existing sessions preserved)
✓ Security improved (httpOnly cookies vs localStorage)
✓ Add mobile browser test to prevent regressionCommon Pitfalls
- Vague symptoms: "It's broken" → Describe exact observable behavior
- Missing environment details: Can't reproduce without knowing context
- No investigation plan: Random attempts waste time, systematic approach faster
- Stopping at fix: Without understanding root cause, likely to recur
Documentation Template
Use for: READMEs, API docs, guides, tutorials, code comments.
Structure
Write [DOC_TYPE] for [TARGET_AUDIENCE]
Purpose: [What reader will learn/accomplish after reading]
Audience:
- Skill level: [Beginner/Intermediate/Expert]
- Domain knowledge: [What they already know]
- What they're trying to accomplish: [Their goal]
Required sections:
1. [Section name]: [What to cover, level of detail]
2. [Section name]: [What to cover, level of detail]
3. [Section name]: [What to cover, level of detail]
For each section:
- Include code examples with explanations
- Highlight common pitfalls and how to avoid them
- Provide practical use cases
Tone: [Helpful/Professional/Technical/Friendly]
Depth: [Overview/Intermediate/Comprehensive]
Format:
- [Markdown/RST/other]
- Code blocks with syntax highlighting
- [Tables/diagrams if needed]
Success criteria:
Reader can [accomplish goal] without additional help or needing to read source codeExample Usage
Write API reference documentation for the User Management API, targeting frontend developers integrating it for the first time.
Purpose: Enable frontend devs to integrate user auth and management features without backend support
Audience:
- Skill level: Intermediate frontend developers
- Domain knowledge: Familiar with REST APIs, HTTP, JSON, but new to our system
- Goal: Integrate login, user profile, and account management features
Required sections:
1. Authentication: How to get and use JWT tokens
- Login flow with example
- Token refresh mechanism
- Handling auth errors
2. User endpoints: CRUD operations for users
- GET /users/:id (fetch profile)
- PUT /users/:id (update profile)
- DELETE /users/:id (delete account)
3. Error handling: Common errors and how to handle them
- 401 Unauthorized → redirect to login
- 403 Forbidden → show "permission denied"
- 429 Rate Limited → show "too many requests, try again in X seconds"
For each endpoint:
- Purpose and when to use it
- Request format (headers, body) with curl example
- Response format (success and error cases) with JSON examples
- Common pitfalls
- "Don't forget to include Authorization header"
- "User IDs must be UUIDs, not integers"
Tone: Professional but helpful. Explain non-obvious behavior, skip REST basics they already know.
Depth: Intermediate—enough detail to integrate successfully, not exhaustive edge cases
Format:
- Markdown
- Syntax-highlighted code blocks (JSON, curl, JavaScript)
- Table for error codes
- Callout boxes for important warnings
Success criteria:
✓ Frontend dev can implement login, profile view, and account deletion
✓ Common integration mistakes are prevented by warnings
✓ Error handling is clear and actionable
✓ Zero questions asked in Slack after readingCommon Pitfalls
- Wrong audience level: Too basic for experts, too advanced for beginners
- Missing examples: Abstract descriptions without concrete code
- No common pitfalls: Users hit same issues repeatedly
- Outdated: Docs don't match current implementation
Exploration Template
Use for: Codebase discovery, pattern finding, understanding architecture, learning new systems.
Structure
Explore [CODEBASE/AREA] to understand [SPECIFIC_ASPECT]
Goals:
- [What to discover]
- [Patterns to identify]
- [Questions to answer]
Scope:
- [What to explore]: [Whole codebase / specific directory / specific feature]
- [What to skip]: [Known areas / out of scope]
Exploration approach:
1. Start with [entry points]: [files/functions to begin investigation]
2. Map [relationships/dependencies]: [How components connect]
3. Identify [key patterns/conventions]: [Recurring structures]
4. Document [findings organized by category]
Questions to answer:
- [Specific question 1]
- [Specific question 2]
- [Specific question 3]
Output format:
- Summary of [architecture/patterns discovered]
- Key files with their purposes
- Findings organized by [category]
- Diagrams [if helpful for understanding]
Stop condition: [When is exploration complete]Example Usage
Explore the authentication system to understand how user sessions are managed.
Goals:
- Understand session lifecycle (create, validate, refresh, expire)
- Identify where session data is stored
- Find all middleware that checks authentication
- Map the flow from login to protected route access
Scope:
- Explore: src/auth/, src/middleware/, database schema for sessions
- Skip: Frontend components (focusing on backend only), OAuth providers (out of scope for now)
Exploration approach:
1. Start with login endpoint (src/auth/login.ts)
- Trace: credentials → validation → session creation → response
2. Map session storage
- Database tables: sessions, users
- Cache layer: Redis keys
3. Identify auth middleware
- Find all files importing requireAuth or similar
- Document: what each middleware checks, what routes use it
4. Document flow with sequence diagram
Questions to answer:
- How long do sessions last? (TTL in database vs cache)
- What triggers session refresh? (Automatic vs manual)
- How are expired sessions cleaned up? (Cron job? Lazy deletion?)
- Can users have multiple sessions? (Different devices)
- What data is stored in session? (User ID only vs full profile)
Output format:
- Summary: "Sessions stored in PostgreSQL (persistence) + Redis (fast lookup). 7-day expiry with sliding window. One session per device."
- Key files:
- src/auth/login.ts: Creates sessions on successful login
- src/auth/middleware.ts: validateSession() checks Redis then DB
- src/jobs/cleanup-sessions.ts: Cron job removes expired sessions (runs daily)
- database/migrations/002_sessions.sql: Session table schema
- Session lifecycle flow:
1. Login → create session in DB + cache in Redis
2. Request → middleware checks Redis (fast) → if miss, check DB
3. Activity → extends expiry (sliding window, resets on each request)
4. Logout → delete from DB + Redis
5. Expiry → cron job cleanup (daily at 2am)
- Findings:
- Redis cache prevents DB hit on every request (perf optimization)
- Sliding window: Active users stay logged in indefinitely
- Each device gets separate session (tracked by device_fingerprint)
- Session stores only user_id and created_at (profile fetched separately)
Stop condition: Can answer all questions about session lifecycle, have mapping of key filesCommon Pitfalls
- Unfocused exploration: "Understand the codebase" too vague → Specify what aspect
- No stop condition: Explore forever without clear completion criteria
- Poor organization: Findings dumped without structure → Hard to reference later
- Missing "why": Document what code does without explaining design decisions
Implementation Template
Use for: Feature building, coding, algorithm implementation, system building.
Structure
Implement [FEATURE/COMPONENT] that [CORE_FUNCTIONALITY]
Requirements:
Functional:
- [What it must do - feature 1]
- [What it must do - feature 2]
- [What it must do - feature 3]
Non-functional:
- Performance: [Response time, throughput, resource usage targets]
- Security: [Auth, validation, data protection requirements]
- Reliability: [Error handling, availability expectations]
Constraints:
- Use [libraries/frameworks]: [Specific tech stack]
- Follow [patterns/conventions]: [Existing code patterns to match]
- Compatible with: [Existing systems/APIs/data formats]
- Don't use: [Things to avoid, with reasoning]
Error handling:
- [Scenario 1]: [How to handle - retry? fail? log?]
- [Scenario 2]: [How to handle]
- [Scenario 3]: [How to handle]
Testing:
- Unit tests for: [Components to test]
- Integration tests for: [End-to-end scenarios]
- Test these edge cases:
- [Edge case 1]
- [Edge case 2]
- Coverage target: [Percentage or specific scenarios]
Success criteria:
✓ [Requirement 1 met and verified]
✓ [Requirement 2 met and verified]
✓ Tests pass with [coverage target]
✓ No breaking changes to existing functionality
✓ [Performance target met]Example Usage
Implement rate limiting middleware for Express.js API that prevents abuse while allowing legitimate usage.
Requirements:
Functional:
- Limit requests per user per time window
- Support different limits for different user tiers (free: 100/hr, pro: 1000/hr)
- Return clear error messages when limit exceeded
- Include headers showing remaining quota
Non-functional:
- Performance: Add <5ms latency to requests
- Security: Prevent bypass via IP spoofing, multiple accounts
- Reliability: Continue serving requests if Redis fails (degrade gracefully)
Constraints:
- Use Redis for distributed rate limiting (multiple app instances)
- Follow existing middleware pattern (req, res, next signature)
- Compatible with current JWT auth middleware (extracts user_id)
- Don't use: Third-party rate limiting libraries (build in-house for learning)
Error handling:
- Rate limit exceeded: Return 429 with Retry-After header, don't crash
- Redis connection error: Log error, allow request through (fail open for availability)
- Invalid user tier: Default to free tier limits
- Missing user_id: Apply IP-based rate limit (stricter, 50/hr)
Testing:
- Unit tests for:
- Rate limit calculation logic
- Different user tiers
- Redis key generation
- Integration tests for:
- Sequential requests hitting limit
- Concurrent requests (race conditions)
- Redis failure fallback
- Test these edge cases:
- User switching tiers mid-hour (how to handle quota?)
- Clock skew across servers
- Redis eviction policy (what if keys disappear early?)
- Coverage target: 85%+ lines, 100% branches for core logic
Implementation notes:
- Use sliding window algorithm (more accurate than fixed window)
- Redis key format: `ratelimit:{user_id}:{timestamp_bucket}`
- Store: sorted set with timestamps, remove old entries before checking
Success criteria:
✓ Free users limited to 100 requests/hour
✓ Pro users limited to 1000 requests/hour
✓ 429 response includes Retry-After header with seconds to wait
✓ Response headers include X-RateLimit-Remaining
✓ Redis failure degrades gracefully (logs error, allows requests)
✓ Latency <5ms for rate limit check (verified with benchmarks)
✓ Tests achieve 85%+ coverage
✓ Existing API functionality unchangedCommon Pitfalls
- Vague requirements: "Add auth" → Specify exact auth method, where, how
- Missing error handling: Happy path only → Production needs failure handling
- No testing strategy: Code without tests → Regressions inevitable
- Undefined success: "Make it work" → Define what "works" means measurably
Planning Template
Use for: Architecture design, approach design, project planning, task breakdown.
Structure
Design approach for [PROJECT/FEATURE]
Goals:
- [Primary objective - the main thing to accomplish]
- [Secondary objectives - nice-to-haves]
Constraints:
- Technical: [Existing systems, tech stack, compatibility requirements]
- Resources: [Team size, skill level, time available]
- Budget: [Infrastructure costs, licensing]
- Timeline: [Deadlines, milestones]
Current state:
- [Relevant existing architecture]
- [Systems this will interact with]
- [Technical debt or limitations to consider]
Unknowns to resolve:
- [Question 1 needing investigation]
- [Question 2 needing decision]
- [Question 3 with multiple valid approaches]
Expected output:
1. Recommended approach with rationale
2. Alternative approaches with trade-offs
3. Phased implementation plan
4. Risk assessment (what could go wrong)
5. Decision points needing user input
6. Success criteria and validation strategy
Design considerations:
- Scalability: [How to handle growth]
- Maintainability: [How to keep it understandable]
- Security: [How to protect against threats]
- Performance: [How to meet speed requirements]
Success criteria:
✓ Clear, actionable plan that team can execute
✓ Trade-offs explicitly documented
✓ Risks identified with mitigation strategies
✓ All major technical decisions have rationaleExample Usage
Design approach for adding real-time collaboration features to document editor.
Goals:
- Primary: Enable 2-10 users to edit same document simultaneously
- Secondary: Show live cursors, typing indicators, presence awareness
Constraints:
- Technical: React frontend, Node.js backend, PostgreSQL database
- Resources: 2 backend engineers, 1 frontend engineer, 6 weeks
- Budget: <$500/month infrastructure increase
- Timeline: MVP in 6 weeks, full release in 10 weeks
Current state:
- Documents stored in PostgreSQL (JSON column for content)
- REST API for CRUD operations (not real-time)
- No WebSocket infrastructure yet
- Frontend uses Draft.js for editor
Unknowns to resolve:
- Conflict resolution strategy: OT (Operational Transform) vs CRDT (Conflict-free Replicated Data Type)?
- How to handle user disconnections and reconnections?
- What's acceptable latency for "feels real-time"? (<100ms, <500ms?)
Expected output:
1. Recommended approach: CRDT with Yjs
Rationale:
- CRDTs are easier to reason about than OT (less complexity)
- Yjs has good Draft.js integration (faster implementation)
- Works offline-first (better UX for flaky connections)
- Widely used, battle-tested (lower risk)
2. Alternative approaches:
Option A: Operational Transform (Google Docs style)
✅ Pros: Minimal data transfer, mature theory
❌ Cons: Complex implementation, hard to debug, 8+ weeks to build
Trade-off: Best efficiency, but beyond timeline/team expertise
Option B: Simple last-write-wins with WebSocket
✅ Pros: Simplest implementation, 2 weeks to MVP
❌ Cons: Users overwrite each other, poor UX, conflict resolution manual
Trade-off: Fast to ship but unacceptable UX for collaboration
3. Phased implementation plan:
Phase 1 (weeks 1-2): Infrastructure
- Add WebSocket server (Socket.io)
- Room management (users join/leave document)
- Presence tracking (who's online)
Phase 2 (weeks 3-4): CRDT integration
- Integrate Yjs with Draft.js
- Sync document changes via WebSockets
- Handle basic conflict resolution
Phase 3 (weeks 5-6): Polish
- Live cursors and selection highlights
- Typing indicators
- Offline support with sync on reconnect
Phase 4 (weeks 7-10): Production hardening
- Load testing (100+ concurrent users per document)
- Error handling (disconnects, network issues)
- Monitoring and alerting
4. Risk assessment:
- Risk: Yjs learning curve → Mitigation: Spike in week 1 to validate
- Risk: WebSocket scaling → Mitigation: Use Socket.io with Redis adapter
- Risk: Data model change → Mitigation: Keep old API, add new for collab
- Risk: Timeline slip → Mitigation: Phase 3 (live cursors) is optional for MVP
5. Decision points:
- Latency target: Confirm <200ms is acceptable (affects infrastructure)
- Document size limits: How big can documents be? (affects performance strategy)
- Concurrent user limit: 10 users or plan for 100? (affects scaling approach)
6. Success criteria:
✓ 2+ users can edit simultaneously without data loss
✓ Changes appear within 200ms
✓ Handles network disconnects gracefully
✓ Infrastructure cost <$500/month at 1000 daily active users
✓ MVP ships in 6 weeksCommon Pitfalls
- Solution before problem: Jumping to "use technology X" without evaluating alternatives
- Ignoring constraints: Designing ideal solution that's not feasible with resources
- No trade-off analysis: Presenting one approach without explaining what you're giving up
- Vague phases: "Then we implement" → Break into concrete, measurable milestones
Refactoring Template
Use for: Code improvement, restructuring, technical debt reduction, pattern extraction.
Structure
Refactor [CODE/COMPONENT] to improve [SPECIFIC_ASPECT]
Current problems:
- [Issue 1 with current code]
- [Issue 2 with current code]
- [Issue 3 with current code]
Goals:
- [Improvement 1]: measured by [metric]
- [Improvement 2]: measured by [metric]
- [Improvement 3]: measured by [metric]
Constraints:
- Preserve existing functionality (all current behavior must work)
- Maintain public API (no breaking changes for consumers)
- No breaking changes without explicit user approval
- [Other constraints: performance, compatibility]
Testing strategy:
1. Add tests for current behavior (if missing)
2. Refactor incrementally (small, verifiable changes)
3. Verify tests still pass after each change
4. Add new tests for improved structure
Refactoring approach:
1. [Step 1]: [What to change, why]
2. [Step 2]: [What to change, why]
3. [Step 3]: [What to change, why]
Success criteria:
✓ [Goal 1 metric achieved]
✓ All existing tests pass
✓ No regressions in functionality
✓ [Code quality metrics improved]: [e.g., complexity, duplication]Example Usage
Refactor the authentication middleware to improve testability and reduce complexity.
Current problems:
- 150-line function doing too much (auth validation + session management + logging)
- Direct database queries mixed with business logic (hard to test)
- Cyclomatic complexity of 15 (target: <10)
- Duplicate error handling across multiple branches
- No tests (too coupled to test easily)
Goals:
- Testability: Each component testable in isolation (measured by: can mock dependencies)
- Complexity: Reduce cyclomatic complexity to <10 (measured by: static analysis)
- Maintainability: Clear separation of concerns (measured by: SRP compliance)
- Test coverage: Achieve 80%+ coverage (measured by: coverage report)
Constraints:
- Preserve existing functionality (all current auth flows must work identically)
- Maintain public API (middleware signature: (req, res, next) => void unchanged)
- No breaking changes (existing routes using this middleware unaffected)
- Performance: No measurable latency increase (current: ~8ms, must stay <10ms)
Testing strategy:
1. Add integration tests for current behavior
- Valid token → req.user populated, next() called
- Invalid token → 401 response
- Missing token → 401 response
- Expired token → 401 response
2. Refactor incrementally with tests passing after each step
3. Add unit tests for extracted functions
4. Verify integration tests still pass
Refactoring approach:
Step 1: Extract validation logic
- Create validateToken(token) function
- Returns: { valid: boolean, decoded: object | null, error: string | null }
- Why: Separate validation concern, easy to unit test
- Tests: Mock JWT library, test various token scenarios
Step 2: Extract session management
- Create getSession(userId) function
- Returns: Session object or null
- Why: Database query separated from middleware, can mock in tests
- Tests: Mock database, test session retrieval
Step 3: Extract error handling
- Create sendAuthError(res, errorType) function
- Why: Centralize error response formatting, reduce duplication
- Tests: Verify correct status codes and response formats
Step 4: Simplify main middleware
- Use extracted functions
- Reduce to: validate → getSession → attach to req → next()
- Why: Main logic now clear, <20 lines, complexity <5
Step 5: Add comprehensive tests
- Unit tests for each extracted function
- Integration test for middleware with mocked dependencies
- Coverage report: Aim for 80%+
Before (complexity 15, 150 lines):async function authMiddleware(req, res, next) { try { const token = req.headers.authorization?.split(' ')[1]; if (!token) { return res.status(401).json({ error: 'No token provided' }); } // ... 140 more lines of validation, session lookup, error handling } catch (error) { // ... complex error handling } }
After (complexity 4, 30 lines):async function authMiddleware(req, res, next) { const token = extractToken(req); if (!token) return sendAuthError(res, 'MISSING_TOKEN');
const validation = await validateToken(token); if (!validation.valid) return sendAuthError(res, validation.error);
const session = await getSession(validation.decoded.userId); if (!session) return sendAuthError(res, 'SESSION_NOT_FOUND');
req.user = session.user; next(); }
Success criteria:
✓ Cyclomatic complexity reduced from 15 to <10
✓ All existing auth flows work identically (verified by integration tests)
✓ 80%+ test coverage achieved
✓ Each function <30 lines
✓ No duplicate error handling code
✓ Latency remains <10ms (verified by benchmarks)
✓ No breaking changes to public APICommon Pitfalls
- Refactor without tests: Risk breaking existing behavior
- Big bang refactor: Rewrite everything at once → hard to debug if something breaks
- Unclear success: "Make it cleaner" → Define what "cleaner" means measurably
- Ignoring performance: Refactor adds abstraction layers that slow things down
Review Template
Use for: Code review, design review, PR review, quality assessment.
Structure
Review [ARTIFACT] focusing on [ASPECTS]
Review criteria:
- [Criterion 1]: [What to check, standards to apply]
- [Criterion 2]: [What to check, standards to apply]
- [Criterion 3]: [What to check, standards to apply]
Context:
- Purpose: [What this code/design is trying to accomplish]
- Audience: [Who will maintain/use this]
- Constraints: [Requirements, limitations to consider]
For each finding:
- Severity: [critical/major/minor/nit]
- Location: [Specific file:line or section]
- Issue: [What's wrong or could be improved]
- Suggestion: [How to improve, with example if helpful]
- Rationale: [Why this matters]
Tone: [Constructive/Supportive/Strict]
Output format:
1. Overall assessment (summary in 2-3 sentences)
2. Critical issues (must fix before merging)
3. Major concerns (should fix, may block if unaddressed)
4. Minor suggestions (nice to have, optional)
5. Positive observations (what's done well)
Success criteria:
✓ All [criterion 1] issues identified
✓ Feedback is specific and actionable
✓ Balance between concerns and positivesExample Usage
Review this pull request adding user profile API endpoint, focusing on security, code quality, and test coverage.
Review criteria:
- Security: Input validation, SQL injection prevention, auth/authorization, data exposure
- Code quality: Readability, maintainability, follows project conventions, error handling
- Test coverage: Unit tests for business logic, integration tests for API, edge cases covered
Context:
- Purpose: Add GET /users/:id and PUT /users/:id endpoints for user profile management
- Audience: Junior engineer new to the team, learning our patterns
- Constraints: Must use existing auth middleware, follow RESTful conventions, maintain <100ms p95 latency
Review findings:
CRITICAL ISSUES (must fix):
1. SQL Injection Vulnerability
- Severity: CRITICAL
- Location: src/routes/users.ts:23
- Issue: User ID concatenated directly into SQL queryconst query = SELECT * FROM users WHERE id = '${userId}';
- Suggestion: Use parameterized queriesconst query = 'SELECT * FROM users WHERE id = $1'; const result = await db.query(query, [userId]);
- Rationale: Direct concatenation allows SQL injection attacks. A malicious user could inject `' OR '1'='1` to access all users.
2. Sensitive Data Exposure
- Severity: CRITICAL
- Location: src/routes/users.ts:45
- Issue: Response includes password hash in user objectres.json(user); // user object contains password_hash field
- Suggestion: Exclude sensitive fieldsconst { password_hash, ...safeUser } = user; res.json(safeUser);
- Rationale: Even hashed passwords shouldn't be exposed via API. Reduces attack surface.
MAJOR CONCERNS (should fix):
3. Missing Authorization Check
- Severity: MAJOR
- Location: src/routes/users.ts:18
- Issue: Any authenticated user can update any other user's profile
- Suggestion: Add authorization checkif (req.user.id !== userId && !req.user.isAdmin) { return res.status(403).json({ error: 'Cannot update other users' }); }
- Rationale: Users should only edit their own profiles unless they're admins.
4. Insufficient Error Handling
- Severity: MAJOR
- Location: src/routes/users.ts:28-35
- Issue: Database errors expose stack traces to client} catch (error) { res.status(500).json({ error: error.message, stack: error.stack }); }
- Suggestion: Log errors server-side, return generic message} catch (error) { logger.error('User fetch failed', { userId, error }); res.status(500).json({ error: 'Failed to fetch user' }); }
- Rationale: Stack traces leak implementation details and file paths to attackers.
MINOR SUGGESTIONS (nice to have):
5. Magic Number
- Severity: MINOR
- Location: src/routes/users.ts:40
- Issue: Hardcoded `403` status code without explanation
- Suggestion: Use named constant or add commentconst HTTP_FORBIDDEN = 403; res.status(HTTP_FORBIDDEN).json(...);
- Rationale: Improves readability, easier to maintain consistently.
6. Missing Input Validation
- Severity: MINOR
- Location: src/routes/users.ts:51
- Issue: PUT request doesn't validate email format
- Suggestion: Add validation with helpful errorif (!isValidEmail(updateData.email)) { return res.status(400).json({ error: 'Invalid email format', field: 'email' }); }
- Rationale: Catch invalid data early with clear feedback.
7. Test Coverage Gap
- Severity: MINOR
- Location: tests/users.test.ts
- Issue: No test for user updating another user's profile (should 403)
- Suggestion: Add test caseit('returns 403 when user tries to update another user', async () => { const response = await request(app) .put('/users/other-user-id') .set('Authorization', Bearer ${userToken}) .send({ name: 'Hacker' }); expect(response.status).toBe(403); });
- Rationale: This is a security-critical path that should be tested.
POSITIVE OBSERVATIONS:
✅ Clean, readable code structure
✅ Good use of async/await (no callback hell)
✅ Appropriate HTTP status codes for success cases
✅ Tests included (good practice for new code)
✅ Follows project naming conventions
OVERALL ASSESSMENT:
This PR adds useful functionality with clean structure, but has critical security issues that must be addressed before merging. The SQL injection vulnerability and password exposure are serious concerns. Once the critical and major issues are fixed, this will be solid work. Nice job including tests—just need a few more edge cases covered.
**Recommendation: Request changes (critical issues must be fixed)**Common Pitfalls
- Only negative feedback: Demoralizes, doesn't reinforce good practices
- Vague criticism: "This is bad" → Explain why and how to improve
- Missing severity: Treating all issues equally → Can't prioritize
- Prescriptive without rationale: "Do it this way" → Explain why
Security Template
Use for: Vulnerability analysis, threat modeling, security audits, penetration testing planning.
Structure
Security analysis of [SYSTEM/CODE]
Scope: [What to analyze - specific component, full system, API surface]
Threat model:
- Attacker profile: [Capabilities, motivation, access level]
- Assets to protect: [Data, functionality, availability]
- Attack vectors to consider: [List of threat categories]
Analysis approach:
1. Identify potential vulnerabilities
2. Assess severity using [CVSS / Internal framework]
3. Propose mitigations
4. Prioritize fixes by risk
For each finding:
- Vulnerability: [Description]
- Attack scenario: [How it could be exploited]
- Impact: [What attacker could achieve]
- Severity: [Critical/High/Medium/Low + score]
- Affected component: [Specific code/config location]
- Mitigation: [How to fix, with code example if applicable]
- Effort to fix: [Hours/days estimate]
Output format:
1. Executive summary (critical findings)
2. Detailed findings (prioritized by severity)
3. Quick wins (easy fixes with high impact)
4. Long-term recommendations
Success criteria:
✓ All [severity level] vulnerabilities identified
✓ Mitigations are actionable and specific
✓ Risk accurately assessedExample Usage
Security analysis of user authentication API endpoints.
Scope:
- POST /auth/login
- POST /auth/register
- POST /auth/refresh
- POST /auth/logout
- Related middleware: authMiddleware, rateLimitMiddleware
Threat model:
- Attacker profile:
- External attacker on internet
- Moderate technical skill
- Motivation: Account takeover, data theft
- Access: Public API endpoints only (no internal network access)
- Assets to protect:
- User credentials and PII
- User sessions and authentication tokens
- Account integrity (prevent unauthorized access)
- Attack vectors:
- Brute force attacks
- SQL injection
- Session hijacking
- Token manipulation
- Account enumeration
Analysis approach:
1. Review authentication logic for common vulnerabilities (OWASP Top 10)
2. Test input validation on all endpoints
3. Analyze session management for weaknesses
4. Check rate limiting effectiveness
5. Review error messages for information leakage
FINDINGS:
[CRITICAL] SQL Injection in Login Endpoint
- Vulnerability: User input concatenated into raw SQL query
- Location: src/auth/login.ts:45const query = SELECT * FROM users WHERE email = '${email}';
- Attack scenario:
1. Attacker sends email: `admin'--`
2. Query becomes: `SELECT * FROM users WHERE email = 'admin'--'`
3. Comment operator `--` ignores password check
4. Attacker gains access to admin account without password
- Impact: Full account takeover of any user, data breach
- Severity: CRITICAL (CVSS 9.8)
- Mitigation:const query = 'SELECT * FROM users WHERE email = $1'; const result = await db.query(query, [email]);
- Effort: 30 minutes
[HIGH] No Rate Limiting on Login Endpoint
- Vulnerability: Unlimited login attempts allow brute force attacks
- Location: src/auth/login.ts (no rate limiting middleware applied)
- Attack scenario:
1. Attacker enumerates common emails (info@, admin@)
2. Brute forces passwords using dictionary (10k attempts/minute)
3. Eventually guesses weak passwords
- Impact: Account compromise, credential stuffing attacks
- Severity: HIGH (CVSS 7.5)
- Mitigation:router.post('/login', rateLimiter({ windowMs: 60000, max: 5 }), // 5 attempts per minute loginHandler );
Plus: Lock account after 10 failed attempts, require CAPTCHA after 3
- Effort: 2 hours
[HIGH] Tokens Don't Expire
- Vulnerability: JWT tokens have no expiration time
- Location: src/auth/jwt.ts:12const token = jwt.sign({ userId }, SECRET); // No exp claim
- Attack scenario:
1. Attacker steals token (XSS, network sniffing, device theft)
2. Token works forever
3. Even if user changes password, old token still valid
- Impact: Indefinite unauthorized access after token theft
- Severity: HIGH (CVSS 7.1)
- Mitigation:const token = jwt.sign( { userId }, SECRET, { expiresIn: '1h' } // Add expiration );
Plus: Implement refresh token rotation
- Effort: 4 hours (including refresh token flow)
[MEDIUM] Account Enumeration via Error Messages
- Vulnerability: Different error messages reveal if email exists
- Location: src/auth/login.ts:55-60if (!user) return res.json({ error: 'Email not found' }); if (!validPassword) return res.json({ error: 'Incorrect password' });
- Attack scenario:
1. Attacker tests emails: attacker submits test@example.com
2. "Email not found" → email doesn't exist
3. "Incorrect password" → email exists, user confirmed
4. Attacker builds list of valid emails for targeted phishing
- Impact: User enumeration, targeted attacks
- Severity: MEDIUM (CVSS 5.3)
- Mitigation:// Same message for both cases return res.json({ error: 'Invalid email or password' });
- Effort: 15 minutes
[MEDIUM] Weak Password Requirements
- Vulnerability: No minimum password strength enforced
- Location: src/auth/register.ts:30 (accepts any non-empty password)
- Attack scenario:
1. Users create weak passwords (e.g., "123456")
2. Easily guessed in brute force attacks
- Impact: Increased success rate of brute force attacks
- Severity: MEDIUM (CVSS 5.0)
- Mitigation:const passwordRequirements = { minLength: 12, requireUppercase: true, requireNumber: true, requireSpecial: true }; if (!meetsRequirements(password, passwordRequirements)) { return res.status(400).json({ error: 'Password must be at least 12 characters with uppercase, number, and special character' }); }
- Effort: 1 hour
[LOW] Session Tokens in URL Parameters
- Vulnerability: Refresh tokens accepted via query parameters
- Location: src/auth/refresh.ts:18const refreshToken = req.query.token || req.body.token;
- Attack scenario:
1. User shares URL accidentally (browser history, server logs, referrer headers)
2. Token leaks via various channels
- Impact: Token exposure through URL logging
- Severity: LOW (CVSS 3.1) - mitigated by short expiry
- Mitigation:// Only accept from body or header, not query params const refreshToken = req.body.token || req.headers['x-refresh-token'];
- Effort: 20 minutes
QUICK WINS (high impact, low effort):
1. Fix SQL injection (CRITICAL, 30 min)
2. Use generic error messages (MEDIUM, 15 min)
3. Remove token from URL params (LOW, 20 min)
Total: ~1 hour for significant security improvement
LONG-TERM RECOMMENDATIONS:
1. Implement comprehensive audit logging (all auth events)
2. Add multi-factor authentication option
3. Conduct regular penetration testing
4. Implement security headers (CSP, HSTS, etc.)
5. Set up intrusion detection monitoring
OVERALL ASSESSMENT:
Critical SQL injection vulnerability must be fixed immediately. No rate limiting makes brute force trivial. Once critical issues addressed, authentication will be reasonably secure for MVP. Recommend security review before production launch.Common Pitfalls
- Generic findings: "Add input validation" → Specify which inputs, how to validate
- Missing attack scenarios: Vulnerability without explaining exploitation path
- No prioritization: All issues treated equally → Can't allocate resources effectively
- Vague mitigations: "Improve security" → Provide specific, actionable fixes
Testing Template
Use for: Test writing, test strategy, QA planning, coverage improvement.
Structure
Write [TEST_TYPE] tests for [COMPONENT/FEATURE]
Test framework: [Jest/pytest/RSpec/etc]
Coverage target: [Percentage OR specific scenarios]
Test scope:
- What to test: [Component/feature boundaries]
- What NOT to test: [External dependencies, framework code]
Critical test cases (priority order):
1. [Scenario]: [Expected behavior]
2. [Scenario]: [Expected behavior]
3. [Scenario]: [Expected behavior]
Edge cases to cover:
- [Edge case 1]: [How to test]
- [Edge case 2]: [How to test]
- [Edge case 3]: [How to test]
Mocking strategy:
- Mock [external dependencies]: [Database, APIs, file system]
- Use real [internal dependencies]: [Utils, helpers]
- Rationale: [Why this mocking strategy]
Test organization:
- File location: [Where tests live]
- Naming convention: [Pattern to follow]
- Setup/teardown: [Test fixtures, database seeding]
- Test grouping: [Describe blocks, categories]
Success criteria:
✓ All critical scenarios covered
✓ Edge cases tested
✓ [Coverage target] achieved
✓ Tests are deterministic (no flakiness)
✓ Tests run in [acceptable time]Example Usage
Write unit and integration tests for the user authentication API endpoint.
Test framework: Jest with Supertest for API testing
Coverage target: 90%+ lines, 100% branches for auth logic
Test scope:
- What to test:
- POST /auth/login endpoint
- Authentication middleware logic
- Token generation and validation
- Error handling paths
- What NOT to test:
- JWT library internals (third-party)
- Express framework behavior (framework)
- Database driver (external)
Critical test cases (priority order):
1. Valid credentials → Returns 200 with JWT token
2. Invalid password → Returns 401 with error message
3. Non-existent email → Returns 401 with generic error (no enumeration)
4. Missing fields → Returns 400 with validation errors
5. Expired token → Returns 401 when accessing protected route
6. Valid token → Populates req.user and allows access
Edge cases to cover:
- SQL injection attempt in email field → Safely handled, no execution
- Very long password (10k chars) → Rejects or handles gracefully
- Concurrent login requests for same user → Both succeed independently
- Token with manipulated payload → Rejected due to signature mismatch
- Token from different environment → Rejected due to different secret
- Whitespace in email/password → Trimmed and handled correctly
Mocking strategy:
- Mock database: Use in-memory SQLite or mock queries
- Rationale: Tests should be fast and not depend on external database
- Trade-off: Some DB-specific behavior not tested (use integration tests)
- Mock password hashing: Use bcrypt with low cost factor (faster tests)
- Rationale: Real bcrypt too slow (100ms per hash), slows test suite
- Use real JWT: Don't mock JWT library
- Rationale: Token generation/validation is core logic to test
Test organization:
- Unit tests: tests/unit/auth.test.ts
- Integration tests: tests/integration/auth-api.test.ts
- Naming: describe('POST /auth/login', () => it('returns 200 for valid credentials'))
- Setup: beforeEach seeds test users, afterEach cleans database
- Grouping: describe blocks by endpoint, nested by scenario type
TEST SUITE STRUCTURE:
Unit tests (tests/unit/auth.test.ts):
describe('validateCredentials', () => { it('returns user for valid credentials', async () => { const user = await validateCredentials('test@example.com', 'correctPassword'); expect(user).toMatchObject({ id: 1, email: 'test@example.com' }); });
it('returns null for invalid password', async () => { const user = await validateCredentials('test@example.com', 'wrongPassword'); expect(user).toBeNull(); });
it('returns null for non-existent email', async () => { const user = await validateCredentials('nonexistent@example.com', 'anyPassword'); expect(user).toBeNull(); }); });
describe('generateToken', () => { it('creates JWT with user ID and expiration', () => { const token = generateToken({ id: 1 }); const decoded = jwt.verify(token, SECRET); expect(decoded).toMatchObject({ userId: 1 }); expect(decoded.exp).toBeDefined(); }); });
describe('validateToken', () => { it('returns decoded payload for valid token', () => { const token = jwt.sign({ userId: 1 }, SECRET, { expiresIn: '1h' }); const result = validateToken(token); expect(result.valid).toBe(true); expect(result.decoded.userId).toBe(1); });
it('returns invalid for expired token', () => { const token = jwt.sign({ userId: 1 }, SECRET, { expiresIn: '-1h' }); const result = validateToken(token); expect(result.valid).toBe(false); expect(result.error).toBe('TOKEN_EXPIRED'); });
it('returns invalid for token with manipulated payload', () => { const token = jwt.sign({ userId: 1 }, 'wrong-secret'); const result = validateToken(token); expect(result.valid).toBe(false); }); });
Integration tests (tests/integration/auth-api.test.ts):
describe('POST /auth/login', () => { beforeEach(async () => { await seedTestUser({ email: 'test@example.com', password: 'SecurePass123!' }); });
describe('success cases', () => { it('returns 200 and JWT for valid credentials', async () => { const response = await request(app) .post('/auth/login') .send({ email: 'test@example.com', password: 'SecurePass123!' });
expect(response.status).toBe(200); expect(response.body.token).toBeDefined(); expect(jwt.verify(response.body.token, SECRET)).toBeDefined(); });
it('allows accessing protected route with returned token', async () => { const loginRes = await request(app) .post('/auth/login') .send({ email: 'test@example.com', password: 'SecurePass123!' });
const profileRes = await request(app) .get('/profile') .set('Authorization', Bearer ${loginRes.body.token});
expect(profileRes.status).toBe(200); expect(profileRes.body.email).toBe('test@example.com'); }); });
describe('error cases', () => { it('returns 401 for incorrect password', async () => { const response = await request(app) .post('/auth/login') .send({ email: 'test@example.com', password: 'WrongPassword' });
expect(response.status).toBe(401); expect(response.body.error).toBe('Invalid email or password'); });
it('returns 401 with generic message for non-existent email', async () => { const response = await request(app) .post('/auth/login') .send({ email: 'nonexistent@example.com', password: 'AnyPassword' });
expect(response.status).toBe(401); expect(response.body.error).toBe('Invalid email or password'); // Same message, no enumeration });
it('returns 400 for missing email', async () => { const response = await request(app) .post('/auth/login') .send({ password: 'SecurePass123!' });
expect(response.status).toBe(400); expect(response.body.error).toContain('email'); }); });
describe('edge cases', () => { it('safely handles SQL injection attempt', async () => { const response = await request(app) .post('/auth/login') .send({ email: "admin'--", password: 'anything' });
expect(response.status).toBe(401); // Not 500, no error thrown expect(response.body.error).toBe('Invalid email or password'); });
it('handles very long password gracefully', async () => { const longPassword = 'a'.repeat(10000); const response = await request(app) .post('/auth/login') .send({ email: 'test@example.com', password: longPassword });
expect(response.status).toBe(401); // Completes without timeout });
it('trims whitespace from email', async () => { const response = await request(app) .post('/auth/login') .send({ email: ' test@example.com ', password: 'SecurePass123!' });
expect(response.status).toBe(200); // Whitespace trimmed, login succeeds }); });
describe('security', () => { it('rejects token with manipulated user ID', async () => { const maliciousToken = jwt.sign({ userId: 999 }, 'wrong-secret');
const response = await request(app) .get('/profile') .set('Authorization', Bearer ${maliciousToken});
expect(response.status).toBe(401); });
it('rejects expired token', async () => { const expiredToken = jwt.sign({ userId: 1 }, SECRET, { expiresIn: '-1h' });
const response = await request(app) .get('/profile') .set('Authorization', Bearer ${expiredToken});
expect(response.status).toBe(401); }); }); });
Success criteria:
✓ All critical scenarios pass (valid/invalid credentials, missing fields)
✓ Edge cases handled (SQL injection, long inputs, whitespace)
✓ Security cases verified (token manipulation, expiration)
✓ 90%+ line coverage (verify with `npm run test:coverage`)
✓ 100% branch coverage for auth logic
✓ All tests pass consistently (no flakiness)
✓ Test suite completes in <10 secondsCommon Pitfalls
- Testing implementation details: Test behavior, not internal structure
- Flaky tests: Time-dependent, race conditions, shared state → Make deterministic
- Over-mocking: Mocking everything → Tests don't catch integration issues
- No edge cases: Only happy path → Production bugs slip through
Troubleshooting Template
Use for: System issues, performance problems, incident response, operational debugging.
Structure
Troubleshoot [SYSTEM/ISSUE]
Symptoms:
- [Observable problem 1]
- [Observable problem 2]
- Started: [When did this begin]
- Frequency: [Constant / Intermittent / Under specific conditions]
Impact:
- Users affected: [All / Specific segment / Percentage]
- Business impact: [Revenue loss / User experience / Data integrity]
- Severity: [Critical/High/Medium/Low]
Urgency: [Critical/High/Medium/Low]
Available tools:
- [Monitoring dashboards]: [URLs or access info]
- [Log access]: [Where to find logs]
- [Diagnostic commands]: [What can be run]
- [System access]: [What environments, what permissions]
Context:
- Recent changes: [Deployments, config changes, traffic spikes]
- Normal baseline: [What "good" looks like]
- Similar past incidents: [Reference to previous issues if applicable]
Investigation approach:
1. Immediate mitigation (if needed to stop bleeding)
2. Gather diagnostic data
3. Form hypotheses (most likely causes)
4. Test hypotheses systematically
5. Identify root cause
6. Implement permanent fix
7. Document findings and prevention
For each hypothesis:
- Theory: [Explanation of what might be wrong]
- Test: [How to validate/invalidate this theory]
- Expected result if theory correct: [What you'd observe]
- Actual result: [What you found]
Output:
- Immediate mitigation (if needed)
- Root cause analysis
- Permanent fix recommendation
- Prevention strategies (how to avoid in future)Example Usage
Troubleshoot API response time degradation causing timeout errors.
Symptoms:
- API response times increased from ~200ms to ~5000ms
- Users experiencing timeout errors (504 Gateway Timeout)
- Started: Today at 14:30 UTC
- Frequency: Constant since start, all endpoints affected
- Error rate: ~30% of requests timing out
Impact:
- Users affected: All users (~10k daily active)
- Business impact: Critical - users cannot complete core workflows
- Revenue impact: Estimated $5k/hour in lost transactions
- Severity: CRITICAL
Urgency: CRITICAL (requires immediate attention)
Available tools:
- Application logs: CloudWatch /aws/lambda/api-prod
- Database monitoring: RDS Performance Insights
- APM: Datadog dashboard (app.datadoghq.com/dash/api-prod)
- Infrastructure: AWS Console, can restart services
- Diagnostic: Can run queries against DB, check Redis cache
Context:
- Recent changes:
- Deploy at 14:00 UTC (30 minutes before issue)
- No infrastructure changes
- No unusual traffic spike (normal load: 100 req/min)
- Normal baseline:
- p50: ~150ms, p95: ~300ms, p99: ~500ms
- Error rate: <0.1%
- Similar past incidents:
- Last month: Similar issue caused by missing database index (fixed)
INVESTIGATION:
Hypothesis 1: Recent deployment introduced performance regression
- Theory: Code deployed at 14:00 has inefficient query or blocking operation
- Test: Check git diff for performance-sensitive changes
- Expected: Find suspicious database query or API call added
- Result: ✓ CONFIRMED
- New feature added: bulk user export
- Query: `SELECT * FROM users` (no LIMIT, fetches all 500k users)
- Called on every request due to bug in middleware
Hypothesis 2: Database connection exhaustion
- Theory: App consuming all DB connections, requests queue
- Test: Check RDS connection count metrics
- Expected: Connection count at max (100), queue building up
- Result: ✓ PARTIALLY CONFIRMED
- Connection count: 98/100 (near max)
- Caused by Hypothesis 1 (slow query holds connections longer)
Hypothesis 3: Cache failure causing DB load spike
- Theory: Redis cache down, all reads hitting DB
- Test: Check Redis metrics and connection status
- Expected: Redis unavailable or cache hit rate dropped
- Result: ✗ REJECTED
- Redis healthy, cache hit rate normal (~85%)
ROOT CAUSE IDENTIFIED:
Recent deployment introduced bulk user export feature with unoptimized query:
- Query fetches all 500k users without LIMIT
- Takes ~4 seconds to execute
- Runs on every API request due to middleware bug (should only run on export endpoint)
- Consumes DB connections, causing queueing
- Other requests timeout waiting for available connections
IMMEDIATE MITIGATION (stop the bleeding):
1. Rollback deployment to previous versiongit revert HEAD docker build -t api:rollback . kubectl set image deployment/api api=api:rollback
Timeline: 2 minutes to rollback
Expected impact: Response times return to normal, error rate drops
2. Monitor recovery
- Watch dashboard: Response times should drop to <500ms within 1 minute
- Error rate should drop to <1% within 2 minutes
EXECUTED: Rollback completed at 14:55 UTC
RESULT: ✓ Response times returned to ~200ms, error rate <0.1%
PERMANENT FIX:
Fix 1: Add LIMIT and pagination to export query// Before (broken): const users = await db.query('SELECT * FROM users');
// After (fixed): const users = await db.query( 'SELECT * FROM users LIMIT $1 OFFSET $2', [pageSize, offset] );
Fix 2: Remove middleware bug (query shouldn't run on every request)// Before (broken): app.use(exportMiddleware); // Runs on ALL routes
// After (fixed): app.get('/api/export', exportMiddleware, exportHandler); // Only on export route
Fix 3: Add query timeout to prevent runaway queriesconst users = await db.query( 'SELECT * FROM users LIMIT $1 OFFSET $2', [pageSize, offset], { timeout: 5000 } // Fail after 5 seconds );
Fix 4: Add database index on export query sort columnCREATE INDEX idx_users_created_at ON users(created_at); -- Improves sort performance for export
PREVENTION STRATEGIES:
1. Pre-deploy performance testing
- Add load test that exercises new endpoints
- Catch performance regressions before production
2. Query review checklist
- All queries must have LIMIT or WHERE clause
- Code review must check for full table scans
- Enforce via linter rule
3. Query monitoring alerts
- Alert when query execution time >1 second
- Alert when connection pool utilization >80%
- Catch issues before they cause outages
4. Staging environment load testing
- Deploy to staging first
- Run realistic traffic simulation
- Monitor performance for 30 minutes before prod deploy
5. Feature flags for risky changes
- New endpoints behind feature flag
- Gradual rollout (5% → 25% → 100%)
- Quick rollback if issues detected
TIMELINE:
- 14:00 - Deploy with bug
- 14:30 - Issue begins (traffic reaches new code)
- 14:35 - Alerts fire (response time, error rate)
- 14:40 - Investigation begins
- 14:55 - Rollback completed (25 minutes to mitigation)
- 15:10 - Root cause documented
LESSONS LEARNED:
- Full table scan in production is never acceptable
- Middleware placement matters (applies to all routes by default)
- Need pre-deploy load testing to catch this class of bug
- 25 minutes to mitigation is too slow for CRITICAL severity (target: <10 min)
POST-MORTEM: Scheduled for tomorrow, invite: dev team, SRE, PMCommon Pitfalls
- Jumping to solutions: Fix symptoms without understanding root cause → Issue recurs
- Random changes: "Try restarting" without hypothesis → Wastes time, might make it worse
- No mitigation plan: Spending hours debugging while users suffer → Stop bleeding first
- Poor documentation: Solve issue but don't document → Next person starts from scratch
Changelog
All notable changes to the accelint-prompt-manager skill will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
[2.3.0] - 2026-03-20
Changed
- Optimized skill description for better triggering coverage — Complete rewrite based on 20-query trigger evaluation set
- Rationale: After production-readiness audit, ran description optimization to improve activation accuracy across edge cases
- Added explicit coverage for "I don't know where to start" / "kinda lost" colloquialisms (common in user queries but missing from v2.2.0)
- Added "how do I explain/communicate this" use cases (users needing help articulating ideas to others)
- Added "help me figure out what to ask/include" patterns (meta-planning queries)
- Reorganized into 5 clear trigger categories: VAGUE GOALS, UNDEFINED SUCCESS, COMMUNICATION UNCLEAR, AMBIGUOUS REQUIREMENTS, META-PROMPTING
- Added "When in doubt - trigger" guidance to reduce undertriggering (false negatives more costly than false positives for this skill)
- Emphasized core purpose: "help defining WHAT they actually want" (clearer than "vague/unclear requests")
- Description structure improvements:
- Before: Long run-on sentence with examples scattered throughout
- After: Categorized trigger patterns with concrete examples under each category
- Improved scannability for agents evaluating whether to activate skill
- More concrete colloquial phrases ("kinda lost", "idk", "whatever works best")
Trigger Evaluation
- Created 20-query test set covering edge cases:
- Should-trigger (16): Vague goals, undefined success, communication help, ambiguous requirements, meta-learning
- Should-not-trigger (4): Meta-questions about prompting (learning, not optimizing), clear execution requests
- Queries include realistic context: file paths, specific details, personal backstory, colloquial language
Design Decisions
- Aggressive triggering stance: "When in doubt - trigger" reflects that false positives (triggered when unnecessary) are less costly than false negatives (missed opportunities to clarify vague requests)
- Categorization over enumeration: Grouped trigger patterns into 5 categories rather than listing all examples linearly
- Colloquial language: Added informal phrases users actually say ("kinda lost", "idk", "whatever works best") not just formal descriptions
- Core purpose clarity: Lead with "help defining WHAT they actually want" - clearer than abstract "vague/unclear"
Version
- Bumped from 2.2.0 → 2.3.0 (minor version: improved triggering, backward compatible)
[2.2.0] - 2026-03-20
Added
- "Do NOT Load" guidance in progressive disclosure — Added explicit negative triggers for each reference file to prevent unnecessary context loading
- Rationale: Audit revealed missing guidance on when NOT to load references, leading to potential token waste
- Examples: "Do NOT load credit-killing-patterns.md if <3 patterns detected", "Do NOT load frameworks.md if task clearly maps to one framework"
- Impact: Reduces token overhead by preventing over-loading of irrelevant references
- Location: Lines 93-109 in How to Use section
Changed
- Streamlined Phase 1 "Extract Core Intent" — Compressed verbose explanation to single line: "Identify the underlying goal from the request"
- Rationale: Original explanation ("What is the user actually trying to accomplish? Look past the words to the underlying goal") was redundant—Claude already knows intent extraction
- Reduces redundant content from 10% to ~7%
- Location: Line 140 in Phase 1
- Streamlined Step 0 gate question — Condensed verbose explanations for faster reading without losing clarity
- Removed unnecessary phrases like "Before starting the workflow, confirm the user's intent" (redundant with section header)
- Simplified skip conditions from verbose bullets to concise list
- Rationale: Improves readability while preserving all essential information
- Location: Lines 121-132
Audit Results
This release addresses findings from production-readiness audit:
Spec Compliance Audit (accelint-skill-manager):
- Result: 100% PASS - No violations found
- Implemented 2 optimization opportunities identified
Design Quality Audit (skill-judge):
- Result: 109/120 points (90.8%) - Grade A ✅
- Exceeded ≥85/100 target requirement
- Implemented all 3 top improvement recommendations:
1. ✅ Added "Do NOT Load" guidance (D5: Progressive Disclosure 14/15 → target 15/15) 2. ✅ Added 9th anti-pattern about triggering info location (D3: Anti-Pattern Quality 14/15 → target 15/15) 3. ✅ Streamlined Phase 1 to reduce redundancy (D1: Knowledge Delta 17/20 → target 18/20)
Dimension Score Improvements (projected):
- D1: Knowledge Delta: 17/20 → ~18/20 (reduced redundancy from 10% to ~7%)
- D3: Anti-Pattern Quality: 14/15 → ~15/15 (added critical 9th anti-pattern)
- D5: Progressive Disclosure: 14/15 → ~15/15 (added "Do NOT Load" guidance)
- Projected total: 109/120 → ~113/120 (94.2%)
Performance Validation
Next step: Run evals/evals.json test suite (4 test cases) to validate no regressions:
- Test 0: Vague non-technical Excel request
- Test 1: Creative blog post with ambiguous terms
- Test 2: Complex database migration (plan mode recommendation)
- Test 3: Extremely vague request handling
Version
- Bumped from 2.1.0 → 2.2.0 (minor version: production-readiness improvements, backward compatible)
[2.1.0] - 2026-03-20
Added
- Optional file saving capability — After delivering the optimized prompt, skill now offers to save it to a markdown file
- Rationale: Users requested ability to persist optimized prompts for reuse without manual copy-paste
- Implementation: Added
Writeto allowed-tools, prompt delivered first (preventing v1.0.0 workflow issues), then offer save as optional post-delivery action - Suggests default location:
./prompts/optimized-prompt-YYYY-MM-DD.mdor accepts user-specified path - Works for initial prompts and refinements
- Clipboard copy functionality — After delivering the optimized prompt, skill offers to copy it to system clipboard
- Rationale: Provides frictionless copy experience without manual selection
- Implementation: Added
Bashto allowed-tools, uses OS-appropriate clipboard command (pbcopy/xclip/clip) - Detects OS automatically: macOS (pbcopy), Linux (xclip), Windows (clip)
- Works for initial prompts and refinements
- Clean markdown code block formatting — All optimized prompts now delivered in triple-backtick code blocks with
markdownlanguage identifier - Rationale: Makes manual copying trivial in terminal/UI clients that support code block copying
- Fallback for when clipboard command unavailable or user prefers manual copy
Changed
- Frontmatter: Added
Write Bashto allowed-tools (was:Read AskUserQuestion) - "Your Role and Output" section: Updated to clarify file saving is optional AFTER delivering prompt (not instead of)
- Phase 4, Step 4: Renamed from "Deliver Optimized Prompt Directly" to emphasize markdown code block formatting
- Phase 4, Step 5: Expanded to "Offer Post-Delivery Options" with save/copy workflow
- Phase 4, Step 6: Renumbered from Step 5 (was "Offer to Iterate Only")
Design Decisions
- Deliver first, save/copy second: Prevents the workflow blockage that plagued v1.0.0 where agents tried to save files instead of delivering prompts
- Markdown code blocks: Universal format that works across all clients and makes copying easy even without clipboard access
- OS detection for clipboard: Maximizes portability across macOS, Linux, Windows
- Optional, not automatic: User controls whether to save/copy, preventing unwanted file creation
- Refinement support: Save/copy options offered after every delivery (initial + refinements)
Version
- Bumped from 2.0.0 → 2.1.0 (minor version: new optional features, backward compatible)
[2.0.0] - 2026-03-19
BREAKING CHANGE
- Removed task execution capability entirely — Skill now ONLY optimizes prompts, never executes the tasks described in those prompts
- Rationale: The skill's core principle is to optimize prompts as text artifacts, not to fulfill the requests those prompts describe. Offering "execute the task instead" as an option violated this boundary and created confusion about the skill's purpose.
- User feedback: "Why did you not ask my intent when I triggered the skill with a supplied prompt?" revealed that even with the gate question, offering execution as an option undermined the skill's design.
Changed
- Step 0 (Verify Intent): Simplified gate question to clarify skill boundaries
- Old: Offered 3 options including "Execute the task described in the prompt instead"
- New: Asks if user wants prompt optimization or task execution, then clarifies that the skill ONLY does optimization
- If user wants task execution: Instructs them to exit the skill and make the request directly
- Phase 4, Step 5 (Offer to Execute or Iterate): Renamed to "Offer to Iterate Only"
- Removed: "Shall I proceed with this optimized prompt? (meaning: execute the task using the optimized prompt)"
- Added: Explicit warning "NEVER offer to execute the task. Your job ends when you deliver the optimized prompt."
- Iteration offers now focus exclusively on refining the prompt itself
Why This is a Major Version
This is a breaking behavioral change. Previously, the skill could hand off to task execution (v1.4.0 Step 0, option 2). Now, the skill strictly refuses execution and instructs users to exit. Any workflows or integrations expecting the skill to execute tasks will break.
Version
- Bumped from 1.4.0 → 2.0.0 (major version: breaking change to core behavior)
[1.4.0] - 2026-03-19
Added
- Intent verification gate question (Step 0) before starting optimization workflow
- Rationale: Skill was triggering on requests where user wanted task execution, not prompt optimization. For example, when user says "Make a 'prompt-manager' skill using these GitHub references", they want the skill created, not the prompt optimized.
- Gate asks: "Would you like me to: 1) Optimize the prompt, 2) Execute the task, or 3) Something else?"
- Includes skip conditions for obvious prompt optimization requests (explicit keywords, quoted prompts, framework discussions)
- Improves UX by disambiguating user intent upfront
Changed
- Workflow now starts with "Step 0: Verify Intent" before Phase 1
- Added clear handoff language when user wants task execution instead of optimization
Version
- Bumped from 1.3.0 → 1.4.0 (minor version: new UX feature)
[1.3.0] - 2026-03-19
Added
- CRITICAL FIX: Added
allowed-tools: Read AskUserQuestionto frontmatter - Rationale: Skill was spawning Explore agents to fetch GitHub repos mentioned in user prompts instead of treating the entire user input as text to optimize
- Whitelists only Read (for references) and AskUserQuestion (for clarifications)
- Blocks: Agent, WebFetch, WebSearch, Bash, Write, Edit, and all other tools
Changed
- Added anti-pattern: "NEVER try to research or implement the user's request"
- Reinforces technical restriction from allowed-tools with explicit guidance
- Clarifies that URLs and references in prompts are text to optimize, not resources to fetch
- Added clarification to "Your Role and Output" section about not researching external resources
Version
- Bumped from 1.2.0 → 1.3.0
[1.2.0] - 2026-03-19
Changed
- Optimized skill description for aggressive triggering across all domains
- Rationale: Description optimization testing (iteration 1) revealed 0% recall — skill never triggered when it should. Test results showed 100% precision but 0% recall on 20-query eval set (11 should-trigger, 9 should-not-trigger).
- Problem: Original description focused too heavily on explicit "prompt" language and didn't capture vague requests across other domains (writing, analysis, documentation, creative work).
- Failed trigger examples: "make this better", "this is too vague", "analyze sales data", "write a blog post", "I have an idea for an app"
- Solution: Expanded description to explicitly list cross-domain trigger scenarios, added aggressive triggering language, and emphasized "ANY domain" scope
- New approach: Lead with domain breadth ("vague requests across ANY domain — writing, analysis, documentation, code, creative work"), then list specific examples, then add original prompt-optimization triggers
Evaluation Results
- Trigger testing iteration 1: 0% recall (never triggering when it should), 100% precision (never falsely triggering)
- Train set: 46% accuracy (18/39 correct) - all failures were should-trigger cases
- Test set: 50% accuracy (12/24 correct) - all failures were should-trigger cases
- Conclusion: Description was far too conservative, needed aggressive expansion to capture vague requests across all domains
Version
- Bumped from 1.1.0 → 1.2.0 (minor version: significant triggering improvement)
[1.1.0] - 2026-03-19
Changed
- CRITICAL FIX: Added explicit "Your Role and Output" section clarifying that the skill's sole artifact is an optimized prompt
- Rationale: Initial testing (iteration-1) revealed agents getting stuck trying to save files instead of delivering prompts directly. In 2/4 test cases (eval 0, eval 2), agents only output meta-descriptions like "I've completed the 4-phase workflow" without showing actual optimized prompts. This caused 0% and 25% pass rates where skill should have excelled.
- Root cause: Skill didn't explicitly state that file management is NOT part of the workflow
- Fix: Added prominent section explaining: "Your sole artifact is a well-structured, clear prompt. Do NOT save files. Do NOT manage directories. Deliver the optimized prompt directly in your response."
- Updated Phase 4 step 4 from "Provide Optimized Prompt" to "Deliver Optimized Prompt Directly" with explicit warning against file operations
- Updated Phase 4 output description to emphasize direct delivery
Evaluation Results
- Iteration 1 (v1.0.0): 56.25% pass rate (same as baseline), but 2/4 test cases incomplete due to file-saving attempts
- Test cases that worked correctly (v1.0.0):
- creative-blog-post: 100% pass rate (4/4) - excellent systematic analysis
- extremely-vague-short: 100% pass rate (4/4) - comprehensive clarification framework
- Test cases that failed due to workflow issue:
- vague-nontechnical-excel: 25% pass rate (only meta-description output)
- complex-database-migration: 0% pass rate (only meta-description output)
Version
- Bumped from 1.0.0 → 1.1.0 (minor version: significant workflow improvement)
[1.0.0] - 2026-03-19
Added
- Initial skill creation: Complete prompt optimization system with 4-phase workflow
- Phase 1: Intake & Assessment (intent extraction, skill level calibration, complexity detection)
- Phase 2: Pattern Detection (credit-killing patterns, ambiguities, trade-offs)
- Phase 3: Framework Selection & Optimization (CO-STAR, RISEN, RODES application)
- Phase 4: Validation & Handoff (quality checks, execution recommendations)
- Expert knowledge anti-patterns (8 patterns):
- Fabrication techniques (MoE, ToT, GoT) in single-prompt execution
- Inappropriate CoT instructions for reasoning-native models
- Framework name pollution in output
- Context-free optimization
- Vague success criteria
- Missing constraints for creative tasks
- Front-loaded long context (lost-in-the-middle)
- Ambiguous pronouns in multi-step instructions
- Progressive disclosure system:
- SKILL.md: Core workflow (always loaded)
- AGENTS.md: Quick reference TOC (loaded on-demand)
- 8 reference files: Detailed patterns and examples (loaded only when needed)
- 12 prompt templates: Task-specific templates (loaded on explicit request)
- User experience calibration:
- Newcomer support: Gentle questions, explanations, before/after comparisons
- Expert support: Direct pattern citations, concise notes, trade-off presentation
- Plan mode integration:
- Automatic complexity detection with >3 interdependent decisions OR >5 sequential phases
- Clear recommendation with reasoning before proceeding
- Framework-based optimization:
- CO-STAR (format-driven): Context, Objective, Style, Tone, Audience, Response
- RISEN (process-driven): Role, Instructions, Steps, End goal, Narrowing
- RODES (example-driven): Role, Objective, Details, Examples, Sense check
- Reference files (8 files):
- credit-killing-patterns.md: 35 anti-patterns from prompt-master repository
- frameworks.md: Detailed framework selection and application guidance
- complexity-detection.md: Complexity assessment criteria
- plan-mode-triggers.md: When to recommend plan mode
- ambiguity-examples.md: Common ambiguity patterns with resolutions
- safe-techniques.md: 5 proven optimization techniques
- template-selection.md: 12 templates with selection logic
- optimization-examples.md: Before/after prompt transformations
- Prompt templates (12 templates):
- analytical, creative, debugging, documentation, exploration, implementation,
planning, refactoring, review, security, testing, troubleshooting
- Freedom calibration table: Guidance specificity calibrated to task fragility
- Low freedom: Meta-prompts, system prompts
- Medium freedom: Production prompt optimization
- High freedom: Creative prompt design
Rationale
Problem: Users frequently provide vague, ambiguous, or unclear prompts that lack context, constraints, or success criteria. This leads to suboptimal outcomes, wasted iterations, and missed opportunities for leveraging advanced prompting techniques.
Solution: Created systematic prompt optimization workflow that: 1. Detects complexity early and recommends plan mode for complex tasks (preventing rework) 2. Identifies 35+ credit-killing patterns from production failures (prompt-master repository) 3. Applies proven frameworks (CO-STAR, RISEN, RODES) silently without exposing methodology 4. Calibrates to user skill level (newcomer vs expert guidance) 5. Uses progressive disclosure to minimize token usage (load details only when needed)
Key Design Decisions:
- Process pattern (~250 lines): Chosen for multi-phase optimization workflow requiring systematic progression
- Progressive disclosure: SKILL.md + AGENTS.md + 8 references + 12 templates = minimal base load, expand on-demand
- Pushy description: Combat undertriggering by explicitly claiming vague/unclear prompt scenarios
- Silent framework routing: Users care about clarity, not methodology — framework names never appear in output
- Plan mode integration: Complex tasks need design phase before execution to prevent costly rework
Content Sources:
- Primary: prompt-master repository (35 credit-killing patterns, 12 templates, 5 safe techniques)
- Secondary: CO-STAR, RISEN, RODES frameworks with automated selection logic
- Expert knowledge: Production failures, model-specific behaviors, security implications
Success Criteria:
- Triggers on vague/complex prompts without explicit "optimize" keyword
- Accurately detects complexity and recommends plan mode appropriately
- Identifies credit-killing patterns and ambiguities systematically
- Applies appropriate framework based on task type
- Calibrates user experience to skill level
- Uses progressive disclosure effectively (references loaded only when needed)
Version
- Initial release: 1.0.0
{
"skill_name": "accelint-prompt-manager",
"evals": [
{
"id": 0,
"prompt": "ok so i have this excel file with sales data from last quarter and my boss wants me to make it look better and maybe add some charts or something? not sure exactly what she wants but it needs to be done by friday. the file is in my downloads folder, probably called 'Q3_sales_final.xlsx' or something like that",
"expected_output": "Should detect vagueness ('look better', 'maybe', 'or something'), flag missing constraints (what kind of charts? what metrics matter? who's the audience?), and disambiguate success criteria. Should NOT overwhelm a non-technical user with jargon. Should ask clarifying questions to understand what 'better' means in this context.",
"files": [],
"assertions": [
{
"name": "Asks clarifying questions",
"description": "Should ask about what 'look better' means, what charts are needed, what metrics matter, or who the audience is. Should not just dive into execution."
},
{
"name": "Identifies specific ambiguities",
"description": "Should explicitly call out vague terms like 'look better', 'maybe', 'or something' as needing clarification."
},
{
"name": "Avoids technical jargon",
"description": "Should use accessible language for non-engineers. Should not use terms like 'API', 'schema', 'data pipeline', 'ETL', etc. without explanation."
},
{
"name": "Does not accept vague request as-is",
"description": "Should push back on vagueness and help the user define success criteria. Should not say 'I'll make it look better' without clarification."
}
]
},
{
"id": 1,
"prompt": "I need to write a blog post about our new product launch. Make it engaging and professional but also approachable. It should highlight the key features and benefits. Around 800 words.",
"expected_output": "Should detect missing creative constraints (tone examples? target audience? specific features to emphasize? what to avoid? style references?). Should identify ambiguous terms ('engaging', 'professional', 'approachable' can mean different things). Should add structure and constraints while preserving creative freedom. Should apply appropriate framework (likely RODES for creative + examples).",
"files": [],
"assertions": [
{
"name": "Identifies missing creative constraints",
"description": "Should ask about tone examples, target audience, brand voice, style references, or what to avoid."
},
{
"name": "Flags ambiguous quality terms",
"description": "Should recognize that 'engaging', 'professional', 'approachable' mean different things to different people and ask for clarification or examples."
},
{
"name": "Asks about specific features",
"description": "Should inquire which product features to emphasize, what benefits matter most, or what differentiates the product."
},
{
"name": "Provides structure",
"description": "Should offer a framework, outline, or structure for the blog post (e.g., intro/features/benefits/CTA), not just accept the request and write."
}
]
},
{
"id": 2,
"prompt": "We're migrating our customer database to a new system and need to make sure all the data gets transferred correctly, update the API endpoints to point to the new database, modify the authentication flow to work with the new setup, update all the documentation, and then test everything before we go live next month. Also need to make sure the old system stays running during the transition in case we need to roll back.",
"expected_output": "Should detect high complexity (6+ interdependent tasks, rollback requirements, testing needs, documentation). Should RECOMMEND PLAN MODE before proceeding because this has >5 sequential phases with dependencies. Should explain why plan mode is appropriate (preventing costly rework, coordinating phases, handling rollback strategy). If user declines, should still structure the request with clear phases, dependencies, success criteria, and risk mitigation.",
"files": [],
"assertions": [
{
"name": "Recommends plan mode",
"description": "CRITICAL: Should explicitly recommend using plan mode before proceeding. Should use phrases like 'I recommend entering plan mode' or 'this task would benefit from plan mode'."
},
{
"name": "Identifies complexity",
"description": "Should recognize and state that this has >5 sequential phases, multiple interdependencies, rollback requirements, or coordinated changes."
},
{
"name": "Explains plan mode rationale",
"description": "Should explain WHY plan mode helps (e.g., prevents costly rework, helps coordinate phases, designs approach before execution)."
},
{
"name": "Structures if declined",
"description": "If user declines plan mode (or if continuing anyway), should still break the task into clear phases with dependencies, success criteria, and risk mitigation."
}
]
},
{
"id": 3,
"prompt": "help me write something good",
"expected_output": "Should gracefully handle extreme vagueness. Should ask foundational questions to extract ANY context: What are you trying to write? (email, document, code, blog post?). Who is it for? What's the purpose? Should guide the user through articulating their intent without making them feel bad about the vague request. Should be patient and educational for someone who might not know how to ask for help.",
"files": [],
"assertions": [
{
"name": "Asks foundational questions",
"description": "Should ask basic context questions: What are you trying to write? (email, document, code, blog post?) Who is it for? What's the purpose?"
},
{
"name": "Patient and educational tone",
"description": "Should guide the user gently through articulating their intent. Should not be dismissive, frustrated, or condescending about the vague request."
},
{
"name": "Extracts context",
"description": "Should help the user think through and articulate what they actually need. Should provide examples or options if the user is stuck."
},
{
"name": "No premature assumptions",
"description": "Should not assume what 'something' is (code? document? email? story?) without asking. Should not jump to any specific domain without confirmation."
}
]
}
]
}
Ambiguity Examples
Common vague terms and how to resolve them with specific, measurable alternatives.
What
Catalog of frequently-ambiguous terminology in prompts, along with concrete interpretation options and resolution strategies.
Why It Matters
Vague terms create misalignment. "Comprehensive" means different things to different people. Without disambiguation, you're guessing at user intent. Good prompts eliminate guesswork.
---
Resolution Pattern
For each ambiguous term: 1. Identify the vague term 2. Present 2-3 interpretation options with implications 3. Let user decide (never assume) 4. Rewrite with chosen specificity
---
Common Vague Terms
"Comprehensive"
Why ambiguous: Ranges from "covers everything" to "hits main points" depending on context and time constraints.
Interpretation options:
- A) Exhaustive — All edge cases, error conditions, and scenarios [+time, +thoroughness]
- B) Complete — Common scenarios and important edge cases [balanced, most common choice]
- C) Overview — Main functionality with representative examples [+speed, -depth]
Resolution example:
❌ Vague: "Write comprehensive tests for this API" ✅ Specific: "Write tests covering: (1) happy path for each endpoint, (2) auth failures (401/403), (3) rate limiting (429), (4) malformed input (400). Target 80%+ branch coverage."
---
"Fast" / "Quick"
Why ambiguous: Could mean response time, development time, or execution time.
Interpretation options:
- A) Fast response time — Optimize for low latency [may increase complexity]
- B) Fast development — Quick to implement [may sacrifice optimization]
- C) Fast execution — Efficient algorithm [may increase dev time]
Resolution example:
❌ Vague: "Make this API call fast" ✅ Specific: "Optimize this API call for response time <200ms at p95. Use caching, parallel requests, and connection pooling."
---
"Simple" / "Clean"
Why ambiguous: Could mean minimal code, easy to understand, few dependencies, or follows conventions.
Interpretation options:
- A) Minimal code — Fewest lines possible [may sacrifice readability]
- B) Easy to understand — Clear logic and naming [may be more verbose]
- C) Few dependencies — Minimal external libraries [may reinvent wheels]
- D) Follows conventions — Matches existing patterns [depends on codebase style]
Resolution example:
❌ Vague: "Write simple error handling" ✅ Specific: "Write error handling that: (1) uses try/catch consistently, (2) logs errors with context, (3) returns user-friendly messages, (4) follows existing ErrorHandler class pattern."
---
"Better" / "Improve"
Why ambiguous: No baseline, no dimension of improvement specified.
Interpretation options:
- A) Better performance — Faster execution [measure: response time, throughput]
- B) Better readability — Easier to understand [measure: complexity metrics, team review]
- C) Better maintainability — Easier to change [measure: coupling, cohesion]
- D) Better security — Fewer vulnerabilities [measure: security scan results]
Resolution example:
❌ Vague: "Make this code better" ✅ Specific: "Refactor this code for readability: (1) extract magic numbers to named constants, (2) split 50-line function into smaller focused functions, (3) add docstrings explaining non-obvious logic."
---
"Optimize"
Why ambiguous: Optimize for what dimension? Trade-offs exist between dimensions.
Interpretation options:
- A) Speed — Reduce execution time [may increase memory or complexity]
- B) Memory — Reduce RAM usage [may increase execution time]
- C) Cost — Reduce cloud spend [may increase latency]
- D) Maintainability — Easier to change [may not be "optimal" by other metrics]
Resolution example:
❌ Vague: "Optimize this database query" ✅ Specific: "Optimize this query for speed: target <50ms execution time. Add indexes on user_id and created_at. Use EXPLAIN ANALYZE to verify."
---
"Secure"
Why ambiguous: Security has many dimensions, each requiring different approaches.
Interpretation options:
- A) Input validation — Prevent injection attacks [SQL, XSS, command injection]
- B) Authentication — Verify user identity [sessions, tokens, OAuth]
- C) Authorization — Control access [roles, permissions, policies]
- D) Data protection — Encrypt sensitive data [at rest, in transit]
Resolution example:
❌ Vague: "Make this API secure" ✅ Specific: "Add security measures: (1) validate all inputs against schema, (2) require JWT authentication on all endpoints, (3) implement rate limiting (100 req/min per user), (4) sanitize error messages to avoid leaking internals."
---
"Scalable"
Why ambiguous: Scale to what load? Vertical or horizontal? What's the constraint?
Interpretation options:
- A) Vertical scaling — Handle more load on single machine [easier, limited ceiling]
- B) Horizontal scaling — Distribute across machines [complex, nearly unlimited]
- C) Load-specific — Handle 10x current load [concrete target]
- D) Cost-effective scaling — Scale within budget constraint [may limit peak capacity]
Resolution example:
❌ Vague: "Design a scalable architecture" ✅ Specific: "Design architecture to handle 10x current load (100k daily active users → 1M). Use horizontal scaling with stateless application servers, Redis for shared state, PostgreSQL with read replicas. Target: <500ms p95 latency, <$5000/month infrastructure cost."
---
"User-friendly"
Why ambiguous: Friendly for which users? Novices vs experts have opposite needs.
Interpretation options:
- A) Novice-friendly — Guided, explanatory, forgiving [may frustrate experts]
- B) Expert-friendly — Fast, keyboard-driven, powerful [may confuse novices]
- C) Self-explanatory — Intuitive without documentation [limits feature density]
Resolution example:
❌ Vague: "Make this CLI user-friendly" ✅ Specific: "Make CLI novice-friendly: (1) interactive prompts for required args, (2) helpful error messages with examples, (3) --help with concrete use cases, (4) confirm before destructive actions."
---
"Production-ready"
Why ambiguous: Production has different requirements depending on context.
Interpretation options:
- A) MVP — Core functionality works [minimal error handling, no monitoring]
- B) Beta — Works with monitoring [handles common errors, basic logging]
- C) GA — Battle-tested [comprehensive error handling, metrics, alerts, runbooks]
Resolution example:
❌ Vague: "Make this feature production-ready" ✅ Specific: "Prepare for GA launch: (1) add comprehensive error handling with retries, (2) instrument with metrics (latency, error rate, throughput), (3) add alerts for >5% error rate, (4) write runbook for on-call, (5) achieve 90%+ test coverage."
---
"Modern"
Why ambiguous: Modern by what standard? Technology changes rapidly.
Interpretation options:
- A) Latest versions — Newest language/framework features [may be unstable]
- B) Current best practices — Industry-standard patterns [proven but not bleeding edge]
- C) Maintained dependencies — No deprecated/EOL libraries [practical baseline]
Resolution example:
❌ Vague: "Use modern React patterns" ✅ Specific: "Use React patterns from 2024+: (1) functional components with hooks, (2) React Query for data fetching, (3) TypeScript for type safety, (4) Vite for build tooling. Avoid: class components, Redux (unless complex state), Create React App."
---
"Flexible" / "Extensible"
Why ambiguous: Flexible how? Over-engineering for hypothetical future needs is wasteful.
Interpretation options:
- A) Configurable — Runtime configuration via settings [adds complexity]
- B) Pluggable — Can swap implementations [adds abstraction layers]
- C) Future-proof — Won't need rewrite for known upcoming changes [depends on roadmap]
Resolution example:
❌ Vague: "Design a flexible API" ✅ Specific: "Design API to support: (1) adding new payment providers without changing consumers, (2) versioning to avoid breaking changes, (3) configurable rate limits per customer tier. Don't over-engineer for hypothetical needs—extend when requirements are clear."
---
Multi-Term Ambiguity
Sometimes multiple vague terms compound:
Example: "Write a comprehensive, user-friendly guide"
- Comprehensive for whom? (Novices vs experts)
- User-friendly how? (Tutorial vs reference)
- Guide about what specifically? (Getting started vs advanced features)
Resolution approach: Disambiguate each term systematically: 1. Audience: novices or experts? 2. Format: tutorial (step-by-step) or reference (lookup)? 3. Scope: getting started or full feature coverage?
---
Contextual Disambiguation
Sometimes context clarifies ambiguity:
Example 1: "Optimize this sorting algorithm"
- Context: Computer science interview
- Inference: Optimize for time complexity (standard interview focus)
- But still confirm: "Optimize for time complexity? (Standard for interviews, but I can optimize for space if needed)"
Example 2: "Make this API secure"
- Context: Auth endpoint
- Inference: Focus on authentication/authorization
- But still confirm: "Focus on auth security (rate limiting, token validation)? Or also input validation and injection prevention?"
Rule: Use context to guide interpretation, but always confirm assumptions.
---
Resolution Template
When you detect ambiguity:
I noticed "[vague term]" could mean:
- Option A: [interpretation 1] [implication]
- Option B: [interpretation 2] [implication]
- Option C: [interpretation 3] [implication]
Which matches your intent? Or if I'm overthinking, just tell me to proceed with [reasonable default].---
When NOT to Disambiguate
Don't over-disambiguate obvious cases:
Example: User is clearly an expert giving precise technical instructions
- "Use memoization to optimize re-renders"
- Context makes it clear, don't ask "What do you mean by optimize?"
Example: Trivial low-stakes task
- "Add a comment explaining this regex"
- Just pick a reasonable interpretation, no need to ask
Rule: Disambiguate when: 1. High stakes (wrong choice costly) 2. Multiple viable interpretations 3. No clear context clues 4. User will benefit from being explicit
---
Common Mistakes
Mistake 1: Assuming Without Asking Guessing user intent leads to misalignment. "I thought you meant comprehensive as in exhaustive, but you wanted an overview."
Mistake 2: Asking Too Many Questions Bombarding with questions is exhausting. Group related ambiguities, prioritize critical ones.
Mistake 3: Offering Too Many Options More than 3-4 options is decision paralysis. Present most likely interpretations.
Mistake 4: Not Providing Defaults "Which do you prefer?" without guidance makes users do unnecessary work. Recommend when appropriate: "I suggest Option B (balanced approach) unless you have specific constraints."
---
Key Principle
Ambiguity is normal in natural language. The skill isn't avoiding ambiguity—it's detecting and resolving it systematically before execution. Good prompts make implicit assumptions explicit.
Related skills
FAQ
Does this skill complete my original request?
No; it only produces an optimized prompt and explicitly avoids executing or researching the underlying task.
What is the primary delivery format?
The optimized prompt is shown first in a markdown code block in the chat response.
When should it trigger on unclear asks?
The description says to trigger aggressively when multiple valid interpretations exist or success is undefined.