Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jniltinho/9df455bf171e48790f3eb3f648281b1e to your computer and use it in GitHub Desktop.
Save jniltinho/9df455bf171e48790f3eb3f648281b1e 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 provide a standardized, parseable format for commit messages.

Common Prefixes

  • feat: – Introduces a new feature (minor version bump).
  • fix: – Resolves a bug (patch version bump).
  • docs: – Updates documentation only.
  • style: – Adjusts code formatting without logic changes.
  • refactor: – Restructures code without adding features or fixing bugs.
  • perf: – Enhances performance.
  • test: – Adds or improves tests.
  • build: – Modifies build system or dependencies.
  • ci: – Updates CI/CD configuration.
  • chore: – Handles maintenance tasks.

Breaking Changes

Indicate breaking changes explicitly:

  • Add ! after the prefix: feat!: switch to new database schema

  • Or use a BREAKING CHANGE: footer:

    feat: implement new user auth
    
    BREAKING CHANGE: removes support for legacy password hashing
    

Examples

feat: add profile picture upload
fix: resolve null pointer in data fetch
docs: clarify API endpoint usage
style: align code with prettier settings
refactor: consolidate duplicate logic in utils
perf: cache repeated database queries
test: expand coverage for user auth
build: upgrade to Node 18
ci: add linting to PR checks
chore: bump dependency versions

Commit messages are critical infrastructure. They drive versioning, changelogs, and clarity—treat them with precision and respect.

{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