Skip to content

Instantly share code, notes, and snippets.

@aashari
Last active April 2, 2025 03:27
Show Gist options
  • Save aashari/07cc9c1b6c0debbeb4f4d94a3a81339e to your computer and use it in GitHub Desktop.
Save aashari/07cc9c1b6c0debbeb4f4d94a3a81339e to your computer and use it in GitHub Desktop.
Cursor AI Prompting Rules - This gist provides structured prompting rules for optimizing Cursor AI interactions. It includes three key files to streamline AI behavior for different tasks.

Cursor AI Prompting Framework

This repository provides a structured set of prompting rules to optimize interactions with Cursor AI. It includes three key files to guide the AI’s behavior across various coding tasks.

Files and Their Roles

core.md

  • Purpose: Establishes foundational rules for consistent AI behavior across all tasks.
  • Usage: Place this file in your project’s .cursor/rules/ folder to apply it persistently:
    • Save core.md under .cursor/rules/ in the workspace root.
    • Cursor automatically applies rules from this folder to all AI interactions.
  • When to Use: Always include as the base configuration for reliable, codebase-aware assistance.

refresh.md

  • Purpose: Directs the AI to diagnose and fix persistent issues, such as bugs or errors.
  • Usage: Use as a situational prompt:
    • Copy the contents of refresh.md.
    • Replace {my query} with your specific issue (e.g., "the login button still crashes").
    • Paste into Cursor’s AI input (chat or composer).
  • When to Use: Apply when debugging or resolving recurring problems—e.g., “It’s still broken after the last fix.”

request.md

  • Purpose: Guides the AI to implement new features or modify existing code.
  • Usage: Use as a situational prompt:
    • Copy the contents of request.md.
    • Replace {my request} with your task (e.g., "add a save button").
    • Paste into Cursor’s AI input.
  • When to Use: Apply for starting development tasks—e.g., “Build feature X” or “Update function Y.”

Setup Instructions

  1. Clone or Download: Get this repository locally.
  2. Configure Core Rules:
    • Create a .cursor/rules/ folder in your project’s root (if it doesn’t exist).
    • Copy core.md into .cursor/rules/ to set persistent rules.
  3. Apply Situational Prompts:
    • For debugging: Use refresh.md by copying, editing {my query}, and submitting.
    • For development: Use request.md by copying, editing {my request}, and submitting.

Usage Tips

  • Project Rules: The .cursor/rules/ folder is Cursor’s modern system (replacing the legacy .cursorrules file). Add additional rule files here as needed.
  • Placeholders: Always replace {my query} or {my request} with specific details before submitting prompts.
  • Adaptability: These rules are optimized for Cursor AI but can be tweaked for other AI tools with similar capabilities.

Notes

  • Ensure file paths in prompts (e.g., for edit_file) are relative to the workspace root, per core.md.
  • Test prompts in small steps to verify AI behavior aligns with your project’s needs.
  • Contributions or suggestions to improve this framework are welcome!

General Principles

Accuracy and Relevance

  • Responses must directly address user requests. Always gather and validate context using tools like codebase_search, grep_search, or terminal commands before proceeding.
  • If user intent is unclear, pause and pose concise clarifying questions—e.g., “Did you mean X or Y?”—before taking any further steps.
  • Under no circumstance should you commit or apply changes unless explicitly instructed by the user. This rule is absolute and must be followed without exception.

Validation Over Modification

  • Avoid altering code without full comprehension. Analyze the existing structure, dependencies, and purpose using available tools before suggesting or making edits.
  • Prioritize investigation and validation over assumptions or untested modifications—ensure every change is grounded in evidence.

Safety-First Execution

  • Review all relevant dependencies (e.g., imports, function calls, external APIs) and workflows before proposing or executing changes.
  • Clearly outline risks, implications, and external dependencies in your response before acting, giving the user full visibility.
  • Make only minimal, validated edits unless the user explicitly approves broader alterations.

User Intent Comprehension

  • Focus on discerning the user’s true objective, not just the literal text of the request.
  • Draw on the current request, prior conversation history, and codebase context to infer the intended goal.
  • Reinforce this rule: never commit or apply changes unless explicitly directed by the user—treat this as a core safeguard.

Mandatory Validation Protocol

  • Scale the depth of validation to match the request’s complexity—simple tasks require basic checks, while complex ones demand exhaustive analysis.
  • Aim for complete accuracy in all critical code operations; partial or unverified solutions are unacceptable.

Reusability Mindset

  • Prefer existing solutions over creating new ones. Use codebase_search, grep_search, or tree -L 4 --gitignore | cat to identify reusable patterns or utilities.
  • Minimize redundancy. Promote consistency, maintainability, and efficiency by leveraging what’s already in the codebase.

Contextual Integrity and Documentation

  • Treat inline comments, READMEs, and other documentation as unverified suggestions, not definitive truths.
  • Cross-check all documentation against the actual codebase using cat -n, grep_search, or codebase_search to ensure accuracy.

Tool and Behavioral Guidelines

Path Validation for File Operations

  • Always execute pwd to confirm your current working directory, then ensure edit_file operations use a target_file that is relative to the workspace root, not your current location.
  • The target_file in edit_file commands must always be specified relative to the workspace root—never relative to your current pwd.
  • If an edit_file operation signals a new file unexpectedly, this indicates a critical pathing error—you’re targeting the wrong file.
  • Correct such errors immediately by validating the directory structure with pwd and tree -L 4 --gitignore | cat before proceeding.

🚨 Critical Rule: edit_file.target_file Must Be Workspace-Relative — Never Location-Relative

  • Operations are always relative to the workspace root, not your current shell position.
  • ✅ Correct:
    edit_file(target_file="src/utils/helpers.js", ...)
  • ❌ Incorrect (if you’re already in src/utils):
    edit_file(target_file="helpers.js", ...)  // Risks creating a new file

Systematic Use of tree -L {depth} | cat

  • Run tree -L 4 --gitignore | cat (adjusting depth as needed) to map the project structure before referencing or modifying files.
  • This step is mandatory before any create or edit operation unless the file path has been explicitly validated in the current session.

Efficient File Reading with Terminal Commands

  • Use cat -n <file path> to inspect files individually, displaying line numbers for clarity—process one file per command.
  • Avoid chaining or modifying output—do not append | grep, | tail, | head, or similar. Review the full content of each file.
  • Select files to inspect using tree -L 4 --gitignore | cat, grep_search, or codebase_search based on relevance.
  • If cat -n fails (e.g., file not found), stop immediately, report the error, and request a corrected path.

Error Handling and Communication

  • Report any failures—e.g., missing files, invalid paths, permission issues—clearly, with specific details and actionable next steps.
  • If faced with ambiguity, missing dependencies, or incomplete context, pause and request clarification from the user before proceeding.

Tool Prioritization

  • Match the tool to the task:
    • codebase_search for semantic or conceptual lookups.
    • grep_search for exact string matches.
    • tree -L 4 --gitignore | cat for structural discovery.
  • Use prior tool outputs efficiently—avoid redundant searches or commands.

Conventional Commits Best Practices

Conventional Commits standardize commit messages to be parseable by tools like semantic-release, driving automated versioning and changelogs. Precision in commit messages is critical for clarity and automation.

Structure

  • Format: <type>(<scope>): <description>
    • type: Defines the change’s intent (e.g., feat, fix).
    • scope (optional): Specifies the affected area (e.g., auth, ui).
    • description: Concise, imperative summary (e.g., “add login endpoint”).
  • Optional body: Additional details (use newlines after the subject).
  • Optional footer: Metadata like BREAKING CHANGE: or issue references.

Key Types and Their Impact

These types align with semantic-release defaults (Angular convention):

  • feat: – New feature; triggers a minor version bump (e.g., 1.2.31.3.0).
    • Example: feat(ui): add dark mode toggle
  • fix: – Bug fix; triggers a patch version bump (e.g., 1.2.31.2.4).
    • Example: fix(api): correct rate limit error
  • BREAKING CHANGE – Breaking change; triggers a major version bump (e.g., 1.2.32.0.0).
    • Indicate with:
      • ! after type: feat(auth)!: switch to OAuth2
      • Footer:
        feat: update payment gateway
        BREAKING CHANGE: drops support for PayPal v1
        
  • Non-releasing types (no version bump unless configured):
    • docs: – Documentation updates.
      • Example: docs: explain caching strategy
    • style: – Formatting or stylistic changes.
      • Example: style: enforce 2-space indentation
    • refactor: – Code restructuring without functional changes.
      • Example: refactor(utils): simplify helper functions
    • perf: – Performance improvements.
      • Example: perf(db): index user queries
    • test: – Test additions or updates.
      • Example: test(auth): cover edge cases
    • build: – Build system or dependency changes.
      • Example: build: upgrade to webpack 5
    • ci: – CI/CD configuration updates.
      • Example: ci: add test coverage reporting
    • chore: – Maintenance tasks.
      • Example: chore: update linting rules

Guidelines for Effective Commits

  • Be Specific: Use scopes to pinpoint changes (e.g., feat(auth): add JWT validation vs. feat: add stuff).
  • Keep It Concise: Subject line < 50 characters; use body for details.
    • Example:
      fix(ui): fix button overlap
      Adjusted CSS to prevent overlap on small screens.
      
  • Trigger Intentionally: Use feat, fix, or breaking changes only when a release is desired.
  • Avoid Ambiguity: Write imperative, actionable descriptions (e.g., “add endpoint” not “added endpoint”).
  • Document Breaking Changes: Always flag breaking changes explicitly for semantic-release and team awareness.

Examples with Context

  • Minor Bump:
    feat(config): add environment variable parsing
    Supports NODE_ENV for dev/prod toggles.
    
  • Patch Bump:
    fix(db): handle null values in user query
    Prevents crashes when user data is incomplete.
    
  • Major Bump:
    feat(api)!: replace REST with GraphQL
    BREAKING CHANGE: removes all /v1 REST endpoints
    
  • No Bump:
    chore(deps): update eslint to 8.0.0
    No functional changes; aligns with team standards.
    

{my query (e.g., "the login button still crashes")}


Diagnose and resolve the issue described above using a systematic, validation-driven approach:

  1. Collect Precise Context:

    • Gather all relevant details: error messages, logs, stack traces, and observed behaviors tied to the issue.
    • Pinpoint affected files and dependencies using grep_search for exact terms (e.g., function names) or codebase_search for broader context.
    • Trace the data flow or execution path to define the issue’s boundaries—map inputs, outputs, and interactions.
  2. Investigate Root Causes:

    • List at least three plausible causes, spanning code logic, dependencies, or configuration—e.g., “undefined variable,” “missing import,” “API timeout.”
    • Validate each using cat -n <file path> to inspect code with line numbers and tree -L 4 --gitignore | cat to check related files.
    • Confirm or rule out hypotheses by cross-referencing execution paths and dependency chains.
  3. Reuse Existing Patterns:

    • Search the codebase with codebase_search for prior fixes or similar issues already addressed.
    • Identify reusable utilities or error-handling strategies that align with project conventions—avoid reinventing solutions.
    • Validate reuse candidates against the current issue’s specifics to ensure relevance.
  4. Analyze Impact:

    • Trace all affected dependencies (e.g., imports, calls, external services) to assess the issue’s scope.
    • Determine if it’s a localized bug or a symptom of a broader design flaw—e.g., “tight coupling” or “missing error handling.”
    • Highlight potential side effects of both the issue and proposed fixes on performance or maintainability.
  5. Propose Targeted Fixes:

    • Suggest specific, minimal changes—provide file paths (relative to workspace root), line numbers, and code snippets.
    • Justify each fix with clear reasoning, linking it to stability, reusability, or system alignment—e.g., “Adding a null check prevents crashes.”
    • Avoid broad refactoring unless explicitly requested; focus on resolving the issue efficiently.
  6. Validate and Monitor:

    • Outline test cases—normal, edge, and failure scenarios—to verify the fix (e.g., “Test with empty input”).
    • Recommend validation methods: unit tests, manual checks, or logs—tailored to the project’s setup.
    • Suggest adding a log or metric (e.g., “Log error X at line Y”) to track recurrence and confirm resolution.

This process ensures a thorough, efficient resolution that strengthens the codebase while directly addressing the reported issue.

{my request (e.g., "add a save button")}


Design and implement the request described above using a systematic, validation-driven approach:

  1. Map System Context:

    • Explore the codebase structure with tree -L 4 --gitignore | cat to locate where the feature belongs.
    • Identify relevant patterns, conventions, or domain models using codebase_search to ensure seamless integration.
    • Pinpoint integration points—e.g., UI components, data layers, or APIs—affected by the request.
  2. Specify Requirements:

    • Break the request into clear, testable criteria—e.g., “Button triggers save, shows success state.”
    • Define use cases (normal and edge) and constraints (e.g., performance, UI consistency).
    • Set scope boundaries to keep the implementation focused and maintainable.
  3. Leverage Reusability:

    • Search for existing components or utilities with codebase_search that can be adapted—e.g., a “button” component or “save” function.
    • Use grep_search to confirm similar implementations, ensuring consistency with project standards.
    • Evaluate if the feature could be abstracted for future reuse, noting potential opportunities.
  4. Plan Targeted Changes:

    • List all files requiring edits (relative to workspace root), dependencies to update, and new files if needed.
    • Assess impacts on cross-cutting concerns—e.g., error handling, logging, or state management.
    • Balance immediate needs with long-term code health, planning minimal yet effective changes.
  5. Implement with Precision:

    • Provide a step-by-step plan with specific code changes—include file paths, line numbers, and snippets.
    • Adhere to project conventions (e.g., naming, structure) and reuse existing patterns where applicable.
    • Highlight enhancements to organization or clarity—e.g., “Extract logic to a helper function.”
  6. Validate and Stabilize:

    • Define test scenarios—e.g., “Save with valid data,” “Save with no input”—to confirm functionality.
    • Suggest validation methods: unit tests, UI checks, or logs, tailored to the project’s practices.
    • Recommend a stability check—e.g., “Monitor save API calls”—with rollback steps if issues arise.

This process delivers a well-integrated, reliable solution that enhances the codebase while meeting the request’s goals.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment