Skip to content

Instantly share code, notes, and snippets.

@kayluhb
Created January 16, 2026 16:11
Show Gist options
  • Select an option

  • Save kayluhb/67e92c2a4b930dc7a1a1f796c6346a93 to your computer and use it in GitHub Desktop.

Select an option

Save kayluhb/67e92c2a4b930dc7a1a1f796c6346a93 to your computer and use it in GitHub Desktop.
Cursor rules and commands for Python development

--- Cursor Command: prsummary.md --- Agent Prompt: Pull Request Generation

Your task is to review the current branch against main, generate a focused Markdown Pull Request summary, and then use the GitHub CLI to create the PR.

1. Code Review and Comparison

  • Review the changes on the current Git branch compared to the main branch to understand the technical scope of the work.

2. Draft the Pull Request Summary

  • Write a clear and concise Pull Request summary in Markdown format.
  • Crucially, the summary must NOT include the following sections: ## Commits, ## Changes Summary, ## Files Modified, or ## Branch.
  • Focus Areas for the Summary:
    • Technical Changes: Describe what was done technically (e.g., refactoring, new service implementation, state management changes).
    • Relevant Codebase Changes: Point the reviewer directly to the most important files or modules to review (e.g., "The core logic is in src/services/auth.js and component usage is in src/pages/Login.tsx").
    • Steps to Test: Provide a clear, numbered list of steps for the reviewer to easily test and verify the changes.

3. Proof of Life

  • Include a short, professional "Proof of Life" statement at the end of the summary to indicate readiness for review. Use a relevant emoji.

4. GitHub CLI Action

  • After the summary is drafted and saved to a markdown file in a temporary directory, execute the following command to create the pull request:
    • Command: gh pr create --body-file <path-to-markdown-file> --assignee @me --draft
    • Note: Save the summary to /tmp/pr_summary_<timestamp>.md to avoid overwriting any existing files. Replace <path-to-markdown-file> with the actual path. Ensure the assignee is set to the user running the agent (@me). The --draft flag creates the PR as a draft.

Pull Request Summary Template (For Agent Guidance)

Title: [A descriptive, concise title, e.g., "feat(shopify): Implement caching for API requests"]

📋 Summary

  • Brief, human-readable summary of what was built or changed.
  • e.g., "Added smart caching to the dashboard to make it load faster."

🔍 Overview

  • Explain the problem that was solved and how it was solved.
  • Include context about what changed and why it matters.
  • Use natural, conversational language that sounds human.
  • e.g., "The dashboard was slow because it kept making the same API calls. Now it remembers responses and only fetches new data when needed, cutting load times from 3.2s to 1.1s and reducing server requests by 70%."
  • e.g., "Users had to manually navigate to the same documents repeatedly. Now the dashboard shows quick-access buttons for their most-visited documents, saving time and clicks."

⚙️ Technical Changes

  • Briefly describe the main architectural or implementation changes. Use bullet points.

  • Include before/after code examples where helpful to illustrate the changes.

  • For new features that didn't exist before, just show the "after" without a "before" section.

  • e.g., "Introduced a new useCaching hook to manage data fetching and local storage persistence."

  • e.g., "Migrated the user profile state from Redux to the React Context API for simpler management."

  • e.g., "Before: Manual API calls on every component mount. After: Smart caching with localStorage persistence and automatic cache invalidation."

  • e.g., "Before: Complex Redux store with multiple reducers. After: Simple React Context with useReducer for cleaner state management."

  • Use markdown code blocks for before/after code examples:

  • e.g., "Before: Manual API calls on every component mount"

  • ```javascript

  • // Before: Redundant API calls

  • useEffect(() => {

    • fetchData(); // Called on every mount*
  • }, []);

  • ```

  • "After: Smart caching with localStorage persistence"

  • ```javascript

  • // After: Cached with automatic invalidation

  • const {data, loading} = useCaching('users', fetchData, {

    • ttl: 300000, // 5 minutes*
    • persist: true*
  • });

  • ```

  • For new features, just show the implementation:

  • e.g., "New Navigation Tracking: Automatically tracks user navigation patterns"

  • ```javascript

  • // New feature: Navigation tracking

  • const {frequentlyVisited, navigateUrl} = useNavigationTracker();

  • // Shows buttons for recently visited documents

  • ```

🔍 Key Review Areas

  • Specifically call out the most relevant files/directories for the reviewer.
  • e.g., src/hooks/useCaching.ts: Contains the core logic for the new caching mechanism.
  • e.g., src/components/Profile/UserInfo.jsx: Shows the new state consumption pattern.

✅ Steps to Test

  1. List the necessary setup (e.g., "Checkout the branch and run npm install").
  2. *List steps to reproduce/verify the change (e.g., "Navigate to /dashboard and check the browser console. The API should only be called once per

--- End Command ---

---
description:
globs:
alwaysApply: true
---
---
description: Opinionated guidance for python testing
globs: **/*.py
alwaysApply: true
---
# Python Testing Standards
## Test Organization
- Tests are run with poetry
- Tests are stored in the `~/project/tests` directory
- Test files must be named `test_*.py`
- Test functions must be named `test_*`
## Testing Framework
- Use pytest for testing
- Prefer function based tests over class based tests
- Maintain minimum 100% code coverage
- Use decorators for patching where possible
- Use conftest.py to set environment variables
- Do NOT use a class based test
## Test Style
- Don't add doc strings to tests
- Keep tests focused and atomic
- Use descriptive test names
- Follow the Arrange-Act-Assert pattern
- Patch with a decorator where possible
- NEVER import modules inside a test unless it will cause a circular import in the test
- NEVER use conditional assertions
## Example
```python
@patch("requests.request")
def test_process_data_success(mock_request):
# Arrange
data = {"key": "value"}
# Act
result = process_data(data)
# Assert
assert result is True
```
## When Finished.
- Check if you can DRY anything up or simplify anything.
---
description:
globs:
alwaysApply: true
---
# Python Documentation Guidelines
## Function Documentation
All API endpoints must be documented using OpenAPI 3.0.0 format with YAML docstrings. Here's the required structure:
```python
def function_name(param1: type, param2: type) -> return_type:
"""
summary: Clear, concise summary of the endpoint
description: Detailed description of what the endpoint does
tags:
- Category1
- Category2
parameters:
- name: param1
in: query|path|header|cookie
description: Description of param1
required: true|false
schema:
type: string|integer|boolean|array|object
format: date|date-time|email|uuid|etc
example: example_value
requestBody:
description: Description of the request body
required: true|false
content:
application/json:
schema:
type: object
properties:
field1:
type: string
description: Description of field1
example: example_value
responses:
'200':
description: Successful response
content:
application/json:
schema:
type: object
properties:
field1:
type: string
description: Description of field1
example: example_value
'400':
description: Bad request
content:
application/json:
schema:
type: object
properties:
error:
type: string
description: Error message
example: Invalid input
security:
- bearerAuth: []
x-triggers-task: task_name # Optional: Indicates which background task is triggered
Example:
```python
# Example usage
response = requests.post('/api/endpoint', json={'param1': 'value1'})
```
"""
```
## File Documentation
Each Python file containing API endpoints should begin with a module-level docstring that includes:
```python
"""
Description: Overview of the module's purpose and functionality
OpenAPI Info:
title: API Title
version: 1.0.0
description: Detailed API description
contact:
name: Team Name
email: team@example.com
Dependencies:
- List of external dependencies and their purposes
Security:
- bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
Usage:
```python
# Example of how to use this module
from module_name import function_name
```
Notes:
- Any important implementation details or considerations
"""
```
## Class Documentation
API-related classes should be documented following this format:
```python
class ClassName:
"""
summary: Clear description of the class's purpose
description: Detailed description of the class's functionality
properties:
- name: property1
type: string|integer|boolean|array|object
description: Description of property1
example: example_value
methods:
- name: method1
description: Description of method1
parameters:
- name: param1
type: string
description: Description of param1
returns:
type: object
description: Description of return value
Example:
```python
# Example usage
instance = ClassName()
result = instance.method1(param1='value1')
```
Notes:
- Any important implementation details or considerations
"""
```
## Best Practices
1. **Be Specific**: Provide clear, concise descriptions that explain the purpose and behavior
2. **Type Hints**: Always include type hints for parameters and return values
3. **Examples**: Include practical examples that demonstrate common use cases
4. **Edge Cases**: Document any important edge cases or exceptions
5. **Keep Updated**: Documentation should be updated whenever the code changes
6. **Security**: Always document security requirements and authentication methods
7. **Response Codes**: Document all possible response codes and their meanings
8. **Schema Validation**: Include detailed request/response schemas
## Common Sections
- **summary**: Brief description of the endpoint
- **description**: Detailed description of functionality
- **tags**: Categories for grouping endpoints
- **parameters**: Input parameters and their types
- **requestBody**: Request body schema and examples
- **responses**: Response schemas for different status codes
- **security**: Authentication and authorization requirements
- **Example**: Usage examples
- **Notes**: Additional important information
- **x-triggers-task**: Background task information (if applicable)
---
description:
globs:
alwaysApply: true
---
---
description: Opinionated guidance for python quality
globs: **/*.py
alwaysApply: true
---
# Python Code Quality Standards
## Type Hints
- Use type hints for all function parameters and return values
- Use Optional[] for nullable values
- Use Union[] for multiple possible types
- Use TypeVar for generic types
## Code Size Limits
- Maximum cyclomatic complexity: 10
- Maximum function length: 50 lines
- Maximum class length: 200 lines
- Maximum file length: 500 lines
## Example
```python
from typing import Optional, List, TypeVar
T = TypeVar('T')
def process_items(items: List[T], limit: Optional[int] = None) -> List[T]:
"""Process a list of items with optional limit."""
if limit is not None:
return items[:limit]
return items
```
## Best Practices
- Follow PEP 8 style guide
- Use meaningful variable names
- Keep functions focused and single-purpose
- Use list comprehensions for simple transformations
- Use generators for large datasets
---
description: Opinionated guidance for python docstring style
globs: **/*.py
alwaysApply: true
---
# Rule: Python Docstring Style
Strict enforcement of Google-style Python docstrings (PEP 257) across the codebase for IDE hints (VS Code, Pylance, IntelliSense).
## Instructions
- Every **public** function, method, class, and module must have a docstring.
- **Private functions and methods** (names starting with `_`) do **not** require examples, but should have docstrings that are helpful in explaining any complexities.
- Use triple double quotes for all docstrings.
- Follow **Google style docstring format**.
- Start with a one-line summary, then an optional detailed description.
- Include sections for **Args**, **Returns**, and **Raises** when applicable.
- Match parameter names exactly as in the function signature.
- Always document argument types and return types, even if annotated in code.
- Keep docstrings concise and informative for IDE IntelliSense hints.
- Use present tense and imperative mood (e.g., `Return user data.` not `Returns user data.`).
- Line length should not exceed 88 characters.
- Do not describe implementation details unless necessary—focus on *what* and *why*.
- **Do NOT duplicate docstrings** in `__init__.py` functions—let the actual implementation handle documentation.
## Mermaid Diagrams
- **Use Mermaid diagrams** for complex workflows, data flows, and system architectures.
- Add diagrams in **public methods and classes** that orchestrate complex processes.
- Place diagrams in a dedicated **Diagram:** section or within **Note:** sections.
- **Focus on business logic flows** rather than implementation details.
- Keep diagrams **concise and readable** - avoid overly complex visualizations.
- Use **consistent node naming** and clear decision points.
- **Examples of good use cases:**
- Product import/export workflows
- Price synchronization processes
- Data transformation pipelines
- Multi-system integration flows
- **Avoid diagrams for:**
- Simple CRUD operations
- Basic data validation
- Single-purpose utility functions
## Examples
### Basic Function
```python
def fetch_user(user_id: int, active_only: bool = True) -> dict:
"""Retrieve user information from the database.
Args:
user_id (int): The unique ID of the user.
active_only (bool, optional): If True, only fetch active users. Defaults to True.
Returns:
dict: A dictionary containing user details.
Raises:
ValueError: If `user_id` is not valid.
"""
```
### Complex Workflow with Mermaid Diagram
```python
def sync_product_data(self, product_id: str) -> SyncResult:
"""Synchronize product data across multiple systems.
Orchestrates the complete product synchronization workflow between
NetSuite, Sanity CMS, and Shopify with intelligent routing based on
product type and launch dates.
Args:
product_id (str): The unique product identifier.
Returns:
SyncResult: Result object containing sync status and changes.
Diagram:
```mermaid
graph TD
A[NetSuite Product] --> B[Sync Services]
B --> C{Product Type Check}
C -->|Regular Product| D[Sanity Import]
C -->|Outlet Product| E[Shopify Import]
D --> F[Sanity CMS]
E --> G[Shopify Store]
F --> H[Auto Export Service]
H --> I{Launch Date Check}
I -->|Within 30 days| J[Export to Shopify]
I -->|Outside 30 days| K[Skip Export]
J --> G
```
Note:
This method handles both regular products (Sanity) and outlet
products (Shopify) with automatic export based on launch dates.
"""
```
---
description: Preferred import style for project modules
globs: **/*.py
alwaysApply: true
---
# Python Import Style
## Preferred Import Pattern
Use top-level module imports with aliases when importing from other project modules, then access classes/functions via the module namespace.
### Preferred Style
```python
# Top-level imports
from project.server.shopify import services
from project.server.sanity import worker as sanity_worker
# Then use via module namespace
inventory_service = services.ShopifyFetchVariantInventoryService()
sanity_worker.sanity_colorway_inventory_status_sync_with_inventory.delay(...)
```
### Avoid
```python
# Avoid direct imports from submodules
from project.server.shopify.services.variants.fetch_inventory import (
ShopifyFetchVariantInventoryService,
)
from project.server.sanity.worker import sanity_colorway_inventory_status_sync_with_inventory
```
## Rules
1. **Top-level module imports**: Import the parent module (e.g., `services`, `worker`) at the top of the file
2. **Use aliases**: Use descriptive aliases when needed (e.g., `worker as sanity_worker`)
3. **Namespace access**: Access classes, functions, and exceptions via the module namespace (e.g., `services.ShopifyFetchVariantInventoryService`)
4. **Exception**: Third-party packages and standard library imports can use direct imports as needed
## Benefits
- Reduces circular import risks
- Makes dependencies clearer
- Easier to refactor module structure
- Consistent with existing codebase patterns
- Better IDE autocomplete support
## Examples
### Services
```python
# Good
from project.server.shopify import services
service = services.ShopifyProductImporterV2()
# Avoid
from project.server.shopify.services.shopify_product_importer_v2 import ShopifyProductImporterV2
```
### Worker Tasks
```python
# Good
from project.server.sanity import worker as sanity_worker
sanity_worker.sanity_colorway_inventory_status_sync.delay()
# Avoid
from project.server.sanity.worker.tasks import sanity_colorway_inventory_status_sync
```
### Exceptions
```python
# Good
from project.server.shopify import services
try:
...
except services.ShopifyStorefrontAuthenticationError:
...
# Avoid
from project.server.shopify.services.variants.fetch_inventory import ShopifyStorefrontAuthenticationError
```
---
description:
globs:
alwaysApply: true
---
---
description: Opinionated guidance for python performance
globs: **/*.py
alwaysApply: true
---
# Python Performance Standards
## Caching
- Cache expensive computations
- Use functools.lru_cache for function results
- Implement proper cache invalidation
- Consider distributed caching for large applications
## Data Processing
- Use generators for large datasets
- Implement pagination for large result sets
- Use async/await for I/O-bound operations
- Profile code before optimization
## Example
```python
from functools import lru_cache
from typing import List
@lru_cache(maxsize=128)
def expensive_calculation(n: int) -> int:
"""Cache results of expensive calculations."""
return sum(i * i for i in range(n))
def process_large_dataset(items: List[int]) -> List[int]:
"""Process items using a generator."""
return (item * 2 for item in items)
```
## Best Practices
- Use appropriate data structures
- Implement proper indexing for databases
- Monitor memory usage
- Use profiling tools to identify bottlenecks
- Consider using Cython for performance-critical code
---
description:
globs:
alwaysApply: true
---
---
description: Opinionated guidance for python security
globs: **/*.py
alwaysApply: true
---
# Python Security Standards
## Secrets Management
- No hardcoded secrets or credentials
- Use environment variables for sensitive data
- Use a secrets management service in production
- Rotate credentials regularly
## Input Validation
- Validate all user input
- Use parameterized queries for database operations
- Sanitize data before processing
- Use type checking and validation libraries
## Example
```python
import os
from typing import Dict
from pydantic import BaseModel, validator
class UserInput(BaseModel):
username: str
password: str
@validator('username')
def username_must_be_valid(cls, v):
if not v.isalnum():
raise ValueError('Username must be alphanumeric')
return v
# Use environment variables
api_key = os.getenv('API_KEY')
```
## Best Practices
- Use HTTPS for all external communications
- Implement proper authentication and authorization
- Log security-relevant events
- Keep dependencies updated
- Use security linters and scanners
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment