Refocus repository on Claim App and enable Render GitHub deploys.

Remove ProcureFlow/Celery legacy, Cursor rules bundle, and scratch artifacts; add claim API routes, deploy docs with auto-deploy, and a claim-focused README.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Syazwan 2026-06-01 19:58:43 +08:00
parent ca749f2623
commit 2613c9d337
253 changed files with 2469 additions and 22426 deletions

View File

@ -1,3 +0,0 @@
rules/
prompts/
workflows/

View File

@ -1,84 +0,0 @@
---
id: prompt-audits-code-optimization
description: Perform project audit — best practices, conventions, security, performance, scalability
author: Himel Das
---
# Project Audit Prompt
## Goal
Audit the codebase; produce an optimization audit document (path per user). Includes best practices, conventions, security, performance.
## Scope
**Categories** (add as relevant): Testing; Code quality; CI/CD; Security; API; Database; Performance; Scalability; Caching; Observability; Resource.
## Process
1. Scan the whole codebase.
2. For each area: list items; mark Status (✅ Done | Pending); assign Priority (High|Medium|Low), Effort (Low|Medium|—), Impact.
3. Reference project conventions if present.
---
## Output Format
### Summary Table (required)
```markdown
| # | Area | Priority | Effort | Impact | Status |
|---|------|----------|--------|--------|--------|
| 1 | ... | High | Low | ... | ✅ Done |
| 2 | ... | Medium | — | ... | Pending |
```
Order: Done first, Pending last. Sequential # (1..n).
### Section Format
Group by category: `## Code Quality`, `## Performance`, `## Security`, `## Database`, etc. Each item: `### N. Title {✅ Implemented|}`.
**Code items** use **Previous** → **Implemented** or **Recommendation**:
```markdown
### N. Title ✅ Implemented
**Previous:** One-line description of old behavior.
\`\`\`
# Representative snippet of old code (515 lines)
\`\`\`
**Implemented:** One-line description of new behavior.
\`\`\`
# Representative snippet of new code (515 lines)
\`\`\`
Optional: 12 line note (e.g. "Full course fetched only at end").
```
**Pending items** use **Current** + **Recommendation**:
```markdown
### N. Title
**Current:** One-line description.
\`\`\`
# Snippet showing current state
\`\`\`
**Recommendation:** One-line actionable suggestion.
```
**Convention items** (no code change) use **Convention:** or **Current (implemented):** with a short code block.
**Snippets:** Previous/Implemented = 515 lines, actual patterns; omit boilerplate; no full-file dumps. Convention = single block, `...` for elision.
## Suggested Priority (optional)
- **High:** ...
- **Medium:** ...
- **Low:** ...

View File

@ -1,272 +0,0 @@
---
id: prompt-architecture-diagram-generation
description: Prompt for generating comprehensive architectural diagrams using Mermaid syntax for any software project
author: Himel Das
---
# Architecture Diagram Generation
## Purpose
This prompt guides the creation of comprehensive architectural documentation using Mermaid diagrams. It helps visualize system architecture, data flows, component hierarchies, and technology stacks for any software project.
## Input Requirements
When using this prompt, provide:
1. **Project context** - Brief description of the project and its purpose
2. **Technology stack** - List of technologies, frameworks, and libraries used
3. **System components** - Key components, layers, and modules
4. **Data flow requirements** - How data moves through the system
5. **Target file path** - Where the architecture diagram file should be created (optional)
### Target File Path Determination
If target file path is not explicitly provided:
- **First priority**: Use the currently open file in the editor if it exists and is a markdown file
- **Second priority**: Intelligently determine the appropriate file path based on:
- Project structure (typically `docs/architecture-diagram.md` or `docs/architecture.md`)
- Existing documentation directory structure
- Create the file if it doesn't exist in the appropriate location
## Diagram Types to Generate
### 1. System Architecture Overview
Create a top-to-bottom (`graph TB`) diagram showing:
- **Client Layer**: Different client types (web browsers, mobile apps, desktop apps, etc.)
- **Frontend Application**: Framework, UI components, routing, state management
- **Authentication & Authorization**: Auth providers, session management, role-based access
- **API Layer**: API routes, endpoints, and handlers
- **Security System**: Middleware, protection mechanisms, security headers
- **Data Layer**: Static data, database, ORM, data models
- **External Services**: Third-party integrations
- **Build & Deployment**: Deployment platform, environment configuration
**Connections**: Show relationships between components using arrows (`-->`)
**Styling**: Apply color coding to important components using `style` declarations
### 2. Data Flow Architecture
Create a sequence diagram (`sequenceDiagram`) showing:
- **Participants**: User, Browser, Middleware, Auth, Authorization, API, ORM, Database
- **Flow**: Request → Authentication → Authorization → API → Database → Response
- **Alternatives**: Use `alt` blocks to show different scenarios (authorized/unauthorized, success/error)
### 3. Component-Specific Architecture
For major subsystems, create focused diagrams:
- **Authentication Flow**: Sign in/up → Session creation → Permission checking → Route protection
- **Admin Panel**: Resource management, CRUD operations, form system, validation
- **Security System**: Configuration → Components → Protection mechanisms → Hooks
- **PWA/Mobile**: Web app → PWA features → Native app wrapper → Platform features
### 4. Technology Stack Summary
Create a mindmap (`mindmap`) showing:
- Root node with project name
- Main categories (Frontend, Backend, Database, Authentication, etc.)
- Subcategories with specific technologies
- Organized hierarchically
### 5. Component Hierarchy
Create a top-down diagram (`graph TD`) showing:
- Root component (e.g., `_app.tsx` or main entry point)
- Provider components
- Layout components
- Feature components
- Nested component relationships
### 6. API Architecture
Create a left-to-right diagram (`graph LR`) showing:
- **Public APIs**: Unauthenticated endpoints
- **Protected APIs**: Authenticated endpoints
- **API Protection**: Middleware layers, permission checks
- **Data Access**: ORM, database connections
## Mermaid Syntax Guidelines
### Node Definitions
- Use descriptive node IDs in UPPERCASE with underscores (e.g., `API_AUTH`, `USER_TABLE`)
- For labels with special characters (`/`, `*`, etc.), wrap in double quotes: `API_AUTH["/api/auth/*\nDescription"]`
- Use `\n` for line breaks in labels, NOT `<br/>` HTML tags
- For database tables, use cylinder shape: `USER_TABLE[(User Table)]`
- Keep node labels concise but descriptive
### Subgraphs
- Use subgraphs to group related components
- Provide descriptive subgraph labels in quotes: `subgraph "API Layer"`
- Nest subgraphs when appropriate to show hierarchy
### Connections
- Use `-->` for directed connections
- Use `-.->` for optional or conditional connections
- Use `-->>` for return flows in sequence diagrams
- Label connections when needed: `A -->|Label| B`
### Styling
- Apply colors to important nodes: `style NODE_NAME fill:#color`
- Use consistent color scheme:
- Primary framework: Blue tones
- Database: Dark gray/black
- Authentication: Purple/indigo
- Security: Orange/yellow
- Admin: Red/pink
- Deployment: Black
### Common Patterns
```mermaid
# System Architecture
graph TB
subgraph "Layer Name"
NODE1[Node 1]
NODE2[Node 2]
end
NODE1 --> NODE2
style NODE1 fill:#color
# Sequence Diagram
sequenceDiagram
participant A
participant B
A->>B: Request
B-->>A: Response
# Mindmap
mindmap
root((Root))
Category1
Item1
Item2
```
## Process
### 1. Analysis
- Analyze the project structure and codebase
- Identify key components, layers, and relationships
- Understand data flow and authentication mechanisms
- Note external integrations and services
### 2. Diagram Creation
- Start with System Architecture Overview (most comprehensive)
- Create Data Flow Architecture for key user journeys
- Add Component-Specific Architecture for major subsystems
- Include Technology Stack Summary
- Add Component Hierarchy if applicable
- Create API Architecture diagram
### 3. Syntax Validation
- Ensure all node labels with special characters are quoted
- Use `\n` instead of `<br/>` for line breaks
- Verify all node IDs are unique
- Check that all referenced nodes in connections are defined
- Validate Mermaid syntax before finalizing
### 4. Organization
- Use clear section headers for each diagram type
- Add brief descriptions before each diagram
- Group related diagrams together
- Include a summary section with key architectural decisions
### 5. Documentation
- Add a title and brief introduction
- Include a "Key Architectural Decisions" section at the end
- Document important design choices and patterns
- Keep descriptions generic and technology-agnostic where possible
### 6. README Integration
- Locate or create the main README file (typically `README.md` in the project root)
- Add a link to the architecture diagram in an appropriate section:
- **Recommended placement**: After "Quick Start" or "Getting Started" section
- **Alternative placements**: In a "Documentation" section or "Architecture" section
- Use a descriptive section header (e.g., "📐 Architecture" or "Architecture")
- Include a brief description explaining what the diagram contains
- Use relative path from README to architecture diagram file (e.g., `docs/architecture-diagram.md`)
- Format example:
```markdown
## 📐 Architecture
For a detailed overview of the system architecture, including diagrams of the component hierarchy, data flow, authentication, and API structure, see the [Architecture Diagram Documentation](docs/architecture-diagram.md).
```
## Output Format
The final markdown file should:
- Start with a title and brief project description
- Contain multiple Mermaid diagram code blocks
- Each diagram in its own section with a descriptive header
- Use proper markdown formatting
- Include a summary section with architectural decisions
- End with exactly one newline character
## Common Issues and Solutions
### Issue: Lexical errors with special characters
**Solution**: Wrap node labels containing `/`, `*`, or other special characters in double quotes:
```mermaid
# Wrong
API_AUTH[/api/auth/*<br/>Description]
# Correct
API_AUTH["/api/auth/*\nDescription"]
```
### Issue: Line breaks not working
**Solution**: Use `\n` instead of `<br/>`:
```mermaid
# Wrong
NODE[Label<br/>Description]
# Correct
NODE["Label\nDescription"]
```
### Issue: Unrecognized node references
**Solution**: Ensure all nodes are defined before being referenced in connections, and node IDs match exactly (case-sensitive).
## Guidelines
- Keep diagrams generic and reusable - avoid project-specific details that limit reusability
- Use consistent naming conventions across all diagrams
- Group related components logically in subgraphs
- Show clear relationships with well-placed connections
- Apply consistent styling to highlight important components
- Validate Mermaid syntax before finalizing
- Make diagrams readable at different zoom levels
- Avoid overcrowding - split complex systems into multiple focused diagrams
## Remember
- The goal is to create clear, comprehensive architectural documentation
- Diagrams should be self-explanatory with minimal text
- Use consistent patterns and conventions throughout
- Test diagrams render correctly in the target markdown viewer
- Keep content generic and applicable to any project type
- Always validate Mermaid syntax to prevent rendering errors
- **Always link the architecture diagram in the main README** to make it discoverable

View File

@ -1,164 +0,0 @@
---
id: prompt-add-vocabulary-sections
alwaysApply: false
description: Prompt for adding vocabulary sections to educational content, Q&A materials, or topic-based documents with essential words only
author: Himel Das
---
# Add Vocabulary Sections
## Task Description
When given educational content organized by topics or themes (such as Q&A materials, study guides, or topic-based documents), add vocabulary sections that extract and list essential words needed to understand the content. The vocabulary should focus only on necessary terms that appear in questions and correct answers, avoiding unnecessary words from unused options or peripheral content.
## Core Requirements
### Vocabulary Extraction
- **Extract words from questions and correct answers only** - Focus on terms that are essential for understanding the content
- **Exclude unused options** - Do not include vocabulary from incorrect answer choices or options that are not part of the correct answer
- **Identify part of speech** - Determine whether each word is a noun, verb, adjective, adverb, etc.
- **Provide translations** - Include clear English translations for all extracted terms
- **Link to source** - Create links to the specific questions or sections where each word appears
### Content Selection Criteria
Include vocabulary that:
- Appears in question text and is essential for understanding
- Is part of the correct answer or explanation
- Represents key concepts or terminology for the topic
- Is necessary for comprehension of the material
Exclude vocabulary that:
- Only appears in incorrect answer options
- Is peripheral or not essential to understanding
- Is common knowledge that doesn't require explanation
- Appears only in examples or supplementary material
### Format Requirements
Each vocabulary section should include:
1. **Title**: "Vocabulary" or "Essential Vocabulary"
2. **Table format** with four columns:
- **Original Language**: The word or phrase in the original language
- **English**: English translation
- **Part of Speech**: Grammatical category (noun, verb, adjective, adverb, etc.)
- **Used In**: Links to specific questions or sections where the word appears
3. **Placement**: Add vocabulary section below the summary/overview and before the main content
### Table Structure
```
## Vocabulary
| Original Language | English | Part of Speech | Used In |
|-------------------|---------|----------------|---------|
| Word 1 | Translation 1 | noun | [Question 1](#link-1), [Question 5](#link-5) |
| Word 2 | Translation 2 | verb | [Question 2](#link-2) |
```
### Linking Requirements
- Create anchor links to questions using markdown link format: `[Question Title](#anchor-id)`
- Use consistent anchor naming (e.g., lowercase with hyphens)
- Ensure links are clickable and navigate to the correct section
- Group multiple references for the same word in the "Used In" column
### Part of Speech Guidelines
Common parts of speech to identify:
- **noun**: Person, place, thing, or concept
- **verb**: Action or state of being
- **adjective**: Describes or modifies nouns
- **adverb**: Modifies verbs, adjectives, or other adverbs
- **preposition**: Shows relationship between words
- **conjunction**: Connects words, phrases, or clauses
- **pronoun**: Replaces nouns
- **phrase**: Multi-word expression
### Vocabulary Organization
The vocabulary table must be organized according to the following hierarchy:
1. **Basic/Fundamental Words First** - Place basic, fundamental words at the top of the table. These are core words that form the foundation of the topic (e.g., "state", "law", "people"). Basic words typically:
- Are simple, root words without prefixes or suffixes
- Represent fundamental concepts
- Are frequently used throughout the content
- Form the basis for compound or derived words
2. **Group Similar Words Together** - Words that share a root, are related, or are compound words containing the same base should be placed immediately after one another. Similar words include:
- Compound words sharing the same root (e.g., "Rechtsstaat", "Bundesstaat" both contain "Staat")
- Words with the same prefix or suffix
- Related concepts or terms
- Words that are semantically connected
3. **Place Opposites After Similar Words** - Opposite or contrasting words should be placed immediately after their similar counterparts. This helps learners understand relationships and contrasts:
- If "democratic" appears, place "dictatorship" nearby
- If "freedom" appears, place related restrictions nearby
- Group antonyms or contrasting concepts together
**Organization Example:**
```
| Staat | state | noun | ... |
| Gesetze | laws | noun | ... |
| Rechtsstaat | constitutional state | noun | ... |
| Bundesstaat | federal state | noun | ... |
| Diktatur | dictatorship | noun | ... |
| Monarchie | monarchy | noun | ... |
```
In this example:
- "Staat" and "Gesetze" are basic words (top)
- "Rechtsstaat" and "Bundesstaat" are similar (both contain "Staat") - grouped together
- "Diktatur" and "Monarchie" are opposites/contrasts to democratic concepts - placed after similar words
## Process Steps
1. **Analyze content** - Review all questions and correct answers in each topic
2. **Extract essential vocabulary** - Identify words that are necessary for understanding
3. **Filter unnecessary terms** - Remove words that only appear in incorrect options
4. **Identify parts of speech** - Determine grammatical category for each word
5. **Create translations** - Provide clear English translations
6. **Organize vocabulary** - Arrange words according to organization hierarchy:
- Place basic/fundamental words at the top
- Group similar words together sequentially
- Place opposite/contrasting words after their similar counterparts
7. **Generate links** - Create anchor links to source questions
8. **Format table** - Organize vocabulary in the specified table format
9. **Insert section** - Place vocabulary section in appropriate location
## Quality Checklist
Before completion, verify:
- ✅ Only essential vocabulary is included
- ✅ No words from unused/incorrect options
- ✅ All words have correct part of speech
- ✅ Translations are accurate and clear
- ✅ Links navigate to correct questions
- ✅ Table format is consistent
- ✅ Vocabulary section is properly placed
- ✅ All necessary words for understanding are included
- ✅ Basic/fundamental words are at the top
- ✅ Similar words are grouped together sequentially
- ✅ Opposite/contrasting words follow their similar counterparts
## Important Notes
- **Focus on necessity** - Only include vocabulary that is essential for comprehension
- **Avoid redundancy** - Don't include common words that don't need explanation
- **Maintain accuracy** - Ensure translations and parts of speech are correct
- **Keep it practical** - The goal is to help readers understand the content, not create an exhaustive dictionary
- **Be selective** - Quality over quantity - fewer essential words are better than many unnecessary ones
## Use Cases
This prompt can be applied to:
- Q&A materials and study guides
- Topic-based educational content
- Language learning materials
- Technical documentation with terminology
- Any structured content where vocabulary extraction would be helpful

View File

@ -1,51 +0,0 @@
---
id: course-structure-chapter-content
author: Himel Das
description: Guidelines for creating course chapter structure with lesson files, exercises, and directories
---
# Course Structure Guidelines
When creating course chapter directories, follow these structure guidelines:
## File Structure
### Lesson Files
* Create markdown files for video lectures only
* Use sequential numbering starting from 1 (e.g., `1-topic.md`, `2-topic.md`, `3-topic.md`)
* Each lesson file should contain only the title as a level 1 heading (`# Title`)
* Do not include Commands or Summary sections in lesson files initially
### Exercises File
* Create an `exercises.md` file in each chapter directory
* This file will contain all exercises for the chapter
### Directory Structure
* Create an `images/` directory for storing images and screenshots
* Create a `src/` directory for source code files
* Do not create subdirectories within `src/` unless specifically needed
* Keep directories empty initially - they will be populated as content is added
## Example Structure
```
chapter-name/
├── 1-first-lesson.md
├── 2-second-lesson.md
├── 3-third-lesson.md
├── exercises.md
├── images/
└── src/
```
## Rules
* ✅ Use sequential numbering for lesson files
* ✅ Include only the title in lesson markdown files
* ✅ Create `exercises.md`, `images/`, and `src/` directories
* ❌ Do not create subdirectories within `src/` unless needed
* ❌ Do not add Commands or Summary sections to lesson files initially

View File

@ -1,81 +0,0 @@
---
id: course-structure-folder-hierarchy
description: Prompt for creating course folder structure with chapters and lessons from screenshots or chapter overviews, following naming conventions and creating README files
author: Himel Das
---
# Create Course Structure from Screenshots
## Purpose
Create course folder structure with numbered chapters and lessons from screenshots/overviews, following naming conventions and generating README files.
## Input Requirements
Provide: screenshots/chapter overviews, target course directory, optional naming preferences.
## Core Rules
### Numbering Format
For count `c` items at each level:
- `c ≤ 9` → format = `N` (1, 2, 3, ...)
- `c ≥ 10` → format = `NN` (01, 02, 03, ...)
- Apply consistently within each level
**Lesson Numbering**:
- Source shows numbers: use exact, preserve course-wide sequence
- Source doesn't show: number sequentially from `1` or `01` within chapter
- Individual number format: `n < 10``N`, `n ≥ 10``NN`
### Same-Level Items Rule
`visual_level(item) = folder_level(item)`. Only create sections if there's clear hierarchical grouping with nested items.
### Content Guidelines
No copyrighted content. Lesson READMEs: title only. Chapter READMEs: generic descriptions from screenshots.
## Process
### Analyze Screenshots
Extract chapter/lesson titles and descriptions. Count chapters and lessons. Determine hierarchy using **Same-Level Items Rule**. Note if lesson numbers are shown in source.
### Create Folder Structure
**Pattern**: `{N|NN}-{kebab-case-name}` where `{N|NN}` follows **Numbering Format**.
- **Chapters**: `{N|NN}-chapter-name`, sequential from `1` or `01`
- **Lessons**: `{N|NN}-lesson-name`, apply **Lesson Numbering Logic** + **Same-Level Items Rule**
- **Sections** (if hierarchical): `{N|NN}-section-name` → lessons within, apply both rules
### Create README Files
- **Chapter**: `README.md``# Chapter {N|NN}: [Title]` + generic description
- **Lesson**: `README.md``# [Title]`
- Apply **Content Guidelines**, end with exactly `1` newline
## Output Structure
```
course-directory/
├── README.md
├── {N|NN}-chapter-name/
│ ├── README.md
│ ├── {N|NN}-lesson-name/
│ │ └── README.md
│ └── {N|NN}-section-name/ (if hierarchical)
│ ├── README.md
│ └── {N|NN}-lesson-name/
│ └── README.md
└── ...
```
## Guidelines
Follow all **Core Rules** consistently. Use numbered prefixes, lowercase with dashes, concise names. Create README files for all chapters and lessons.
## Verification
Verify: naming = `{N|NN}-{kebab-case}`, **Numbering Format** consistent, sequential numbering, `README.md` present for all chapters/lessons, **Content Guidelines** followed, file endings = `1` newline.

View File

@ -1,121 +0,0 @@
---
id: prompt-create-practice-file-from-questions
alwaysApply: false
description: Generic prompt for creating a practice/recall file from question sets by removing translations while preserving questions and answers
author: Himel Das
---
# Create Practice File from Questions
## Task Description
When given a collection of questions with translations and answer explanations, create a practice file that removes translations from the question text and options while preserving the original questions and answer sections. This enables users to practice recall by reading questions in the target language and checking answers immediately.
## Input Formats
The input can be provided in various formats:
- **Multiple sequential files**: Files numbered sequentially (e.g., `001-050.md`, `051-100.md`, `101-150.md`)
- **Single file**: All questions in one file
- **Files with translations**: Questions containing both source language and translated text
- **Mixed formats**: Combination of the above
## Core Requirements
### Content Processing
- **Remove translations** from question text and answer options (typically text in parentheses)
- **Preserve original language** text exactly as written
- **Remove bold formatting** from question text and options
- **Keep answer sections intact** in their original format with all explanations
- **Maintain question structure** including headings, numbering, and formatting
- **Preserve image references** exactly as they appear
### Answer Section Handling
- **Include answer sections** in the original format
- **Keep all answer content** including explanations and translations
- **Maintain answer formatting** (e.g., `> Answer: **option** - explanation`)
- **Preserve answer structure** for immediate checking
### File Structure
- Create a single consolidated file (e.g., `all.md`, `practice.md`, `recall.md`)
- Include all questions sequentially from the input files
- Maintain original question numbering
- Use appropriate heading structure (e.g., `### Question 1`, `### Aufgabe 1`)
## Process Steps
1. **Read all input files** to understand the structure and format
2. **Identify translation patterns** (typically text in parentheses after original text)
3. **Extract questions** maintaining original structure
4. **Remove translations** from question text and options
5. **Remove bold formatting** from questions and options
6. **Preserve answer sections** in their original format
7. **Combine all questions** into a single file
8. **Verify completeness** - ensure all questions are included
9. **Check formatting** - ensure structure is maintained
## Processing Rules
### Translation Removal
- Remove text in parentheses that appears to be translations
- Preserve the original language text exactly
- Handle cases where translations might be in different formats
- Be careful not to remove important content that happens to be in parentheses
### Formatting Cleanup
- Remove bold markers (`**`) from question text and options
- Preserve other formatting like lists, headings, and line breaks
- Maintain consistent spacing and structure
### Answer Preservation
- Keep answer sections exactly as they appear in the source
- Do not modify answer explanations
- Preserve answer formatting and structure
- Include all answer content for immediate verification
## Output Format
The output file should contain:
```
# Title
### Question 1
[Question text in original language without translations]
- a. [Option without translation]
- b. [Option without translation]
- c. [Option without translation]
- d. [Option without translation]
> Answer: [Original answer format with all content preserved]
### Question 2
...
```
## Quality Checklist
Before completion, verify:
- ✅ All questions are included
- ✅ Translations removed from questions and options
- ✅ Original language text preserved exactly
- ✅ Answer sections included and intact
- ✅ Question numbering maintained
- ✅ Image references preserved
- ✅ File structure is clean and readable
- ✅ No content has been accidentally removed
## Important Notes
- This operation **removes translations** but **preserves original content**
- Answer sections remain **fully intact** for immediate checking
- The goal is to create a **practice/recall file** for language learning
- All original formatting and structure should be maintained where appropriate
- The output enables users to practice by reading questions and checking answers

View File

@ -1,37 +0,0 @@
---
id: prompt-extract-pdf-lessons
description: Extract lesson-wise PDFs from a combined PDF file by identifying lesson start markers
author: Himel Das
---
# Extract PDF Lessons
## Core Rules
**Input** → Single PDF with multiple lessons, each starting with a marker page.
**Output** → Sequential PDFs: `1.pdf`, `2.pdf`, `3.pdf`, ...
**Library** → `pypdf` only.
**Detection** → User-provided hints or intelligent analysis (text patterns, image characteristics, page structure).
**Script Location** → Create extraction script in `scripts/` directory at same level as input PDF.
## Process
### Identify Lesson Start Pages
**With hint**: Use specified pattern (text/image/structure) to detect lesson starts.
**Without hint**: Scan pages intelligently—extract text, identify patterns (title/logo pages, section headers, distinct formatting), use first page as lesson 1 start.
### Extract Lessons
**Python Environment**: Check for virtual environment at repository root (`.venv/`, `venv/`, `env/`). If found → activate and use it; else → use global Python. Create extraction script in `scripts/` directory at same level as input PDF. If `OUTPUT_DIR` not specified → create directory with same name as PDF file (without extension) at same level as input PDF. For lesson `i` (1-indexed): start = marker `i`, end = marker `i+1` (or PDF end for last lesson). Extract pages `[start, end)` → save as `{i}.pdf` in `OUTPUT_DIR`. Create `PdfReader` once, reuse for all extractions. Handle missing markers, empty pages, extraction failures gracefully.
## Constants
- **PDF_PATH**: Input PDF file path
- **OUTPUT_DIR**: Directory for extracted lesson PDFs (default: PDF filename without extension at same level as input PDF if not specified)
- **SCRIPT_DIR**: Directory for extraction script (default: `scripts/` at same level as input PDF)
- **MARKER_PATTERN**: Text/image pattern for lesson start detection (if provided)
## Output & Verification
Sequential numbering (`1.pdf`, `2.pdf`, ...), pages `[start, end)` per lesson, preserve quality. Verify all PDFs created, page counts match ranges, no missing/duplicated pages, files readable. **Validate page count**: Sum of pages in all output PDFs = total pages in input PDF. Print validation results in chat (input pages, output pages per lesson, total output pages, match status).

View File

@ -1,131 +0,0 @@
---
id: prompt-lecture-infographic-generation
author: Himel Das
---
# Lecture Infographic Generation
Create a premium infographic-style lecture diagram in a clean cloud-computing visual style.
⚠️ HARD OUTPUT REQUIREMENT:
- The final image MUST be EXACTLY 16:9 aspect ratio
- Resolution MUST be EXACTLY 1920×1080
- Do NOT generate portrait, square, cropped, or near-16:9 layouts
- Ensure every element fits cleanly inside a true widescreen presentation canvas
- No extra borders or vertical overflow
- Layout must be optimized specifically for PowerPoint/Keynote slides
IMPORTANT DESIGN RESTRICTIONS:
- DO NOT place any AWS logo, company logo, watermark, or branding anywhere
- Avoid copyrighted branding elements
- Use generic cloud-computing visuals and neutral tech icons only
- Maintain a professional enterprise-cloud aesthetic without brand identity
⚠️ STRICT COPYRIGHT & ORIGINALITY RULES:
- The infographic MUST be fully original and newly generated
- DO NOT copy any sentence, phrase, definition, example, analogy, workflow, or explanation directly from the lecture notes
- DO NOT reuse lecture examples, case studies, scenarios, or sample wording
- DO NOT replicate textbook layouts, certification slides, proprietary diagrams, or branded visual structures
- ALL educational content must be transformed into newly written explanations
- Rewrite concepts using completely fresh wording while preserving technical meaning
- Summarize ideas independently instead of paraphrasing line-by-line
- Generate unique teaching-friendly bullets rather than adapted lecture text
- Create original examples and simplified conceptual explanations where needed
- Avoid recognizable copied phrasing from educational materials or online sources
- The final slide should feel like a newly designed professional training asset, NOT a reformatted copy of notes
- Use only generic and newly generated architecture diagrams
- Reconstruct workflows visually from scratch instead of imitating known cloud-provider diagrams
- Ensure all labels, section titles, captions, and callouts are uniquely written
- Do not reproduce copyrighted charts, tables, figures, or illustration styles
- Maintain originality in both textual content and visual composition
STYLE & QUALITY:
- Modern educational infographic
- High-end presentation slide design
- Clean vector graphics
- Professional typography
- Consistent color palette
- Balanced spacing and alignment
- Minimal but visually rich
- White/light background with colored content cards
- Use soft shadows, rounded corners, subtle gradients
- Corporate cloud-tech aesthetic
- Ultra-sharp details
- Presentation-ready quality
LAYOUT:
- Large bold title at top-left
- Minimal icon area at top-right (generic icon only, no logos)
- Multi-section horizontal widescreen layout
- Central process/workflow diagram in the middle
- Supporting information panels around it
- Bottom summary/key takeaways bar
- Use arrows, icons, cloud symbols, server icons, storage icons, maps, and workflow connectors
- Maintain strong horizontal composition suitable for widescreen slides
VISUAL HIERARCHY:
- Each section should have:
- Colored header banner
- Relevant icon
- Short concise bullet points
- Important concepts should be highlighted using:
- contrasting colors
- larger icons
- flow arrows
- emphasis boxes
CONTENT STRUCTURE:
1. Definition / Overview
2. Importance / Purpose
3. Types / Categories
4. Workflow / Architecture Flow
5. Key Components
6. Best Practices / Notes
7. Key Takeaways
GRAPHIC ELEMENTS:
- Use flat modern vector icons
- Include cloud infrastructure visuals
- Use connected arrows for processes
- Add small illustrative diagrams where useful
- Include subtle world map or network visuals for distributed systems topics
- Use clean infographic separators and dividers
TEXT RULES:
- Keep text concise and presentation-friendly
- Use short bullets instead of paragraphs
- Emphasize keywords visually
- Ensure readability from a presentation screen
- Generate concise teaching-focused summaries
- Avoid lengthy technical wording
- Replace copied terminology with simplified original phrasing whenever possible
- Create fresh educational explanations optimized for visual learning
- Do not quote lecture material directly
- Do not preserve original sentence structures from the source
- Convert dense lecture content into visually digestible original summaries
COLOR PALETTE:
- Primary: dark navy blue
- Secondary: orange
- Accent colors: green, purple, cyan
- Neutral whites and light grays
- Consistent professional cloud-tech theme
QUALITY REQUIREMENTS:
- Presentation-ready visual quality
- Clean alignment and spacing
- No clutter
- Consistent icon style
- Sharp typography hierarchy
- Visually balanced composition
- Enterprise-grade educational design
- Similar to premium cloud certification course slides
FINAL OUTPUT EXPECTATION:
- The final infographic must look like an entirely new educational design created from understanding the topic rather than copying lecture material
- The result should be visually original, structurally unique, and textually rewritten from scratch
- Prioritize originality, clarity, and presentation quality over faithfulness to source wording
NOW GENERATE THE INFOGRAPHIC FOR THIS LECTURE:
[PASTE YOUR LECTURE NOTES HERE]

View File

@ -1,455 +0,0 @@
---
id: prompt-notes-generation
author: Himel Das
description: Generate comprehensive study notes from provided resources for any topic with organized directory structure, images, and practice questions
---
# Comprehensive Notes Generation from Resources
Generate complete, well-structured study notes from provided documentation, books, resources, and tips. The notes should serve as a single source of truth for understanding the topic.
## Purpose
Create comprehensive, exam-ready notes from various source materials that consolidate key concepts, practical examples, code snippets, architecture diagrams, and practice questions into an organized, easy-to-study format.
## Input Requirements
* **Topic outline**: Directory structure or list of topics/subtopics to cover
* **Resources**: Any combination of:
* Official documentation (local files or directories)
* Books (PDFs, markdown)
* Study tips or guides
* Architecture diagrams and images
* Code examples
* Reference materials
## Directory Structure Creation
### Automatic Directory Setup
Before generating content, create the following structure:
```
notes/
├── topic-1/
│ ├── subtopic-1/
│ │ ├── assets/
│ │ └── README.md
│ ├── subtopic-2/
│ │ ├── assets/
│ │ └── README.md
│ └── README.md
├── topic-2/
│ ├── subtopic-1/
│ │ ├── assets/
│ │ └── README.md
│ └── README.md
└── README.md
```
### Directory Naming Convention
* Use **kebab-case** for all directory names
* Create an `assets/` folder in each topic/subtopic directory
* Place a `README.md` in each directory to hold the notes
### README Files at Different Levels
Create README files at multiple levels of the directory hierarchy:
**Main README** (`notes/README.md`):
* Comprehensive overview of all topics
* Study strategy and timeline
* Key focus areas across all topics
* Quick reference cheat sheet
* How to use the notes
* Exam/study tips
* Navigation to all sections
**Section README** (e.g., `notes/topic-1/README.md`):
* Overview of what's covered in this section
* Detailed breakdown of subtopics with bullet points
* Why this section matters (relevance)
* Key focus areas for this section
* Study approach specific to this section
* Quick tips and memorable one-liners
* Navigation links to subtopics and other sections
**Subtopic README** (e.g., `notes/topic-1/subtopic-1/README.md`):
* Detailed content with key takeaways
* Core concepts and explanations
* Code examples and practical guidance
* Visual aids and reference tables
* Practice questions
## Content Generation Process
### Step 1: Explore Resources
1. **Read provided directory structure** or topic outline
2. **Identify all available resources**:
* Documentation files (`.rst`, `.md`, `.txt`)
* Books or PDFs
* Tips or study guides
* Image assets
* Code examples
3. **Map resources to topics**: Determine which resources relate to which topics
### Step 2: Deep Content Analysis
For each topic/subtopic:
1. **Read all relevant documentation** deeply and thoroughly
2. **Extract key information**:
* Core concepts and definitions
* Architecture and components
* How things work (step-by-step flows)
* Commands and syntax
* Use cases and examples
* Common patterns and best practices
* Limitations and constraints
3. **Identify important diagrams and images** in the source materials
4. **Note practical tips** from provided study guides
### Step 3: Image Handling
When source materials contain images:
1. **Copy relevant images** to the `assets/` folder of the appropriate topic/subtopic
2. **Use appropriate naming**: Keep original names or rename descriptively
3. **Reference images** in markdown using relative paths:
```markdown
![Description](./assets/image-name.png)
```
4. **Supported image types**: PNG, JPG, SVG, GIF
### Step 4: Content Structure
Different README files have different purposes and structures:
#### Main README Structure (notes/README.md)
1. **Title and Overview**
* Brief description of the study material
* Purpose and context
2. **Study Strategy**
* Week-by-week or phase-by-phase study plan
* How to approach the material
* Time estimates
3. **Topic Overview**
* List of all major sections
* What each section covers
* Exam weight or importance
4. **Key Focus Areas**
* Most important topics across all sections
* Common patterns to remember
* Critical concepts that appear frequently
5. **Quick Reference Cheat Sheet**
* One-page summary of essential information
* Formulas, commands, syntax
* Quick lookup tables
6. **How to Use These Notes**
* For initial study
* For revision
* Before exam/assessment
7. **Tips and Best Practices**
* Exam-taking strategies
* Study tips
* Common pitfalls to avoid
8. **Navigation**
* Links to all major sections
#### Section README Structure (notes/topic-1/README.md)
1. **Section Title**
* What this section covers
2. **Overview and Breakdown**
* Detailed list of subtopics
* What each subtopic contains
* Why this section matters
3. **Key Focus Areas**
* Most important topics in this section
* Specific to this section only
4. **Study Approach**
* How to study this section effectively
* Recommended exercises
* Practical tips
5. **Quick Tips**
* Memorable one-liners
* Key concepts to remember
* Common patterns
6. **Navigation**
* Links to subtopics and other sections
#### Subtopic README Structure (notes/topic-1/subtopic-1/README.md)
1. **Key Takeaways**
* Most important points to remember (use unordered list with bullets)
* Common patterns
* Critical concepts
* Quick summary for revision
2. **Introduction**
* What is this topic?
* Why is it important?
* High-level overview
3. **Core Concepts**
* Key terminology with definitions
* Fundamental principles
* Architecture and components (with diagrams)
* How things work together
4. **Practical Examples**
* Code examples with explanations
* Real-world use cases
* Step-by-step walkthroughs
5. **Commands/Syntax Reference** (if applicable)
* Common commands with examples
* Syntax patterns
* Important flags or options
6. **Visual Aids**
* Architecture diagrams
* Flow charts
* Screenshots (if relevant)
7. **Quick Reference Tables**
* Summary tables for quick lookup
* Comparison tables
* Feature matrices
8. **Practice Questions**
* Multiple choice questions with checkboxes
* Answers with explanations
* Format:
```markdown
**Q1: Question text?**
**Answer**:
- □ Option A
- ✓ Option B (correct)
- □ Option C
- □ Option D
**Explanation**: Why B is correct...
```
## Writing Style Guidelines
### Tone and Language
* **Natural, human-like writing**: Avoid AI-sounding phrases
* **Conversational but informative**: Write like explaining to a colleague
* **Clear and direct**: Start with the answer, not preamble
* **Active voice**: Prefer active over passive constructions
* **Practical focus**: Emphasize "what this means" and "how to use it"
### Formatting Best Practices
* **Bold key terms** when first introduced or emphasized
* **Use inline code** for commands, variables, file names: `command`, `variable`
* **Use code blocks** for examples with proper language tags
* **Use lists** for multiple related items (3+ items)
* **Use tables** for structured comparisons or quick reference
* **Use arrows** for progressions: **Step 1****Step 2** → **Step 3**
* **Use horizontal rules** (`---`) to separate major sections
### Emphasis Guidelines
* **Bold** for key concepts, important terms, section labels
* *Italic* for soft emphasis or temporal aspects
* `Code format` for technical terms, commands, file paths
* **Tables** for structured data and comparisons
* **Superscript** for powers: 10⁴, N², 2ⁿ (not caret notation: 10^4)
## Content Quality Standards
### Accuracy and Completeness
* Extract information directly from provided resources
* Verify technical accuracy against source materials
* Include all critical concepts from the resources
* Don't omit important details
### Practical Focus
* Include code examples with explanations
* Provide real-world use cases
* Show step-by-step processes
* Explain "why" not just "what"
### Organization
* Logical flow from basic to advanced concepts
* Clear section hierarchy (H2, H3, H4)
* Consistent formatting throughout
* Easy to scan and navigate
### Study Effectiveness
* Content should be comprehensive enough to learn from notes alone
* Include practice questions to test understanding
* Provide quick reference sections for review
* Highlight critical points for focused study
## Special Considerations
### Tips Integration
If study tips are provided:
1. **Identify focus areas** mentioned in tips
2. **Emphasize these topics** in the notes
3. **Add exam tips** or "Important!" callouts for these areas
4. **Create extra practice questions** for focus areas
5. **Include tip references**: "Tip from [source]: ..."
### Multiple Source Integration
When multiple resources cover the same topic:
1. **Synthesize information** from all sources
2. **Use most detailed/official** source as primary
3. **Add supplementary details** from other sources
4. **Cross-reference** different perspectives
5. **Maintain consistency** in terminology
## Processing Workflow
1. **Analyze Structure**
* Read provided topic outline
* Understand topic hierarchy
* Identify what needs to be covered
2. **Create Directories**
* Create all topic/subtopic folders
* Create `assets/` folders in each
* Create empty `README.md` files at all levels
3. **Map Resources**
* Identify which resources cover which topics
* Note which images relate to which topics
* Plan content organization
4. **Generate Main README**
* Create comprehensive overview of all topics
* Include study strategy and timeline
* Add quick reference cheat sheet
* Provide exam/study tips
* Add navigation links
5. **Generate Section READMEs**
* For each major section (topic-1, topic-2, etc.)
* Create section overview with subtopic breakdown
* Explain why the section matters
* Provide section-specific study approach
* Add quick tips and navigation
6. **Generate Subtopic Content**
* Start with first subtopic
* Read all relevant source materials deeply
* Copy relevant images to assets folder
* Write comprehensive notes following structure
* Include code examples from sources
* Add practice questions
7. **Review and Refine**
* Verify all topics are covered
* Check all README files exist at appropriate levels
* Check all images are copied and referenced
* Ensure consistent formatting
* Verify technical accuracy
* Test that notes are comprehensive
* Verify navigation links work correctly
## Example Directory After Generation
```
notes/
├── README.md (main overview with study guide, cheat sheet, navigation)
├── fundamentals/
│ ├── README.md (section overview with subtopic breakdown, study approach)
│ ├── basic-concepts/
│ │ ├── assets/
│ │ │ ├── architecture-diagram.png
│ │ │ ├── workflow-chart.png
│ │ │ └── component-view.png
│ │ └── README.md (detailed content with key takeaways, examples, questions)
│ └── advanced-features/
│ ├── assets/
│ │ ├── advanced-architecture.png
│ │ └── use-case-diagram.png
│ └── README.md (detailed content with key takeaways, examples, questions)
└── task-management/
├── README.md (section overview with subtopic breakdown, study approach)
└── operators/
├── assets/
└── README.md (detailed content with key takeaways, examples, questions)
```
## Quality Checklist
### Directory Structure
* [ ] All directories created with proper structure
* [ ] All `assets/` folders exist where needed
* [ ] README files exist at all appropriate levels (main, section, subtopic)
### Content Quality
* [ ] Main README provides comprehensive overview and study guide
* [ ] Section READMEs provide topic breakdown and study approach
* [ ] Subtopic READMEs have detailed content following the structure
* [ ] Key takeaways listed at the beginning of each subtopic for quick revision (using unordered lists)
* [ ] Code examples included with explanations
* [ ] Architecture diagrams and visuals present
* [ ] Quick reference tables included
* [ ] Practice questions with answers included
* [ ] Content is accurate to source materials
* [ ] Notes are comprehensive enough to learn from alone
### Images and References
* [ ] All relevant images copied to appropriate `assets/` folders
* [ ] Images referenced correctly in markdown with relative paths
### Navigation and Formatting
* [ ] Navigation links work correctly between sections
* [ ] Writing style is natural and human-like
* [ ] Formatting is consistent (bold, code, lists, tables)
* [ ] All sections properly separated with spacing
* [ ] Horizontal rules used appropriately for visual separation
### Study Integration
* [ ] Study tips integrated into relevant sections
* [ ] Study strategy provided in main README
* [ ] Quick tips included in section READMEs
* [ ] Exam focus areas highlighted throughout
## Copyright and Attribution
* **DO NOT** copy verbatim text from sources
* **DO** summarize and explain in your own words
* **DO** extract commands, syntax, and technical details
* **DO** credit tips when using them: "Tip: ..."
* **DO** focus on educational transformation of content
## Output Format
* All content in **Markdown** format
* One `README.md` per topic/subtopic
* Images in `assets/` folders
* Proper markdown syntax throughout
* Line ending with single newline character

View File

@ -1,113 +0,0 @@
---
id: prompt-organize-questions-by-topic
alwaysApply: false
description: Generic prompt for organizing questions or content items by topic/theme while preserving all original content and sequence numbers
author: Himel Das
---
# Organize Questions by Topic
## Task Description
When given a collection of questions or content items that are sequentially ordered, organize them into topic-based groups while maintaining all original content exactly as provided. This operation is purely organizational - grouping related items together for easier study and reference.
## Input Formats
The input can be provided in various formats:
- **Multiple sequential files**: Files numbered sequentially (e.g., `001-050.md`, `051-100.md`, `101-150.md`)
- **Single file**: All questions in one file
- **Plain text**: Questions provided as text in the conversation
- **Mixed formats**: Combination of the above
## Core Requirements
### Content Preservation
- **Do not change a single letter** of the original question content
- Preserve all original sequence numbers exactly as they appear
- Maintain all formatting, including markdown, images, code blocks, and special characters
- Keep all answer explanations and metadata exactly as provided
- Preserve image file references and ensure paths remain correct
### Organization Structure
1. **Analyze all questions** to identify common themes and topics
2. **Create topic categories** based on the content themes found
3. **Group related questions** together within each topic
4. **Order similar questions** one after another when they cover the same concept
5. **Maintain sequence numbers** - questions keep their original numbering even when grouped
### File Structure
- Create a `README.md` file listing all topics with brief descriptions
- Create individual topic files (e.g., `01-topic-name.md`, `02-another-topic.md`)
- Use `##` headings for topics in the README
- Use `###` headings for individual questions (maintaining original format)
- Use kebab-case for topic filenames (e.g., `basic-concepts.md`, `advanced-topics.md`)
### Topic Files Format
Each topic file should include:
1. **Title**: Descriptive topic name
2. **Summary**: English summary explaining the key concepts covered in that topic, written so that studying the summary enables answering all questions in that topic
3. **Questions**: All questions belonging to that topic, maintaining original sequence numbers and formatting
### Grouping Rules
- Group questions that share the same core concept or theme
- Place duplicate or very similar questions together (e.g., if the same question appears in multiple versions, group them)
- Order questions logically within each topic (similar questions adjacent to each other)
- Ensure every question is assigned to exactly one topic
- Verify all questions are included (no questions should be missing)
### Image and Resource Handling
- Preserve all image references exactly as they appear in the original
- Ensure image paths remain correct relative to the file structure
- Maintain any other resource references (links, files, etc.)
## Process Steps
1. **Read and analyze** all input files to understand the full scope of questions
2. **Identify topics** by analyzing question content and themes
3. **Create topic structure** in README.md with clear descriptions
4. **Extract and categorize** each question into appropriate topic files
5. **Group similar questions** together within each topic
6. **Add summaries** to each topic file explaining the key concepts
7. **Verify completeness** - ensure all questions are included and properly categorized
8. **Check formatting** - ensure all markdown, images, and special formatting is preserved
## Output Structure
```
target-directory/
├── README.md # Overview with topic list
├── 01-topic-name.md # Topic file with questions
├── 02-another-topic.md # Another topic file
├── ...
└── images/ # Image resources (if applicable)
└── ...
```
## Quality Checklist
Before completion, verify:
- ✅ All original questions are included
- ✅ All sequence numbers are preserved
- ✅ No content has been modified
- ✅ Similar questions are grouped together
- ✅ Each topic has a clear summary
- ✅ Image paths are correct
- ✅ README.md lists all topics
- ✅ File structure is organized and logical
## Important Notes
- This is a **grouping operation only** - no content modification
- Questions maintain their original sequence numbers for reference
- The goal is to make content easier to study by grouping related items
- All original formatting, languages, and structure must be preserved exactly

View File

@ -1,302 +0,0 @@
---
id: prompt-revision-guide-generation
author: Himel Das
description: Guidelines for generating comprehensive revision guides from course lecture materials, extracting commands and summaries for interview preparation
---
# Revision Guide Generation Prompt
Generate comprehensive revision guides from course lecture materials that consolidate commands, summaries, and key concepts for efficient interview preparation and quick reference.
## Purpose
Create a single, well-organized markdown document that serves as a complete reference guide for a course, making it easy to review all commands, concepts, and summaries before interviews or exams.
## Input Requirements
* Course directory structure with lecture markdown files
* Each lecture file should contain Commands and Summary sections
* Course should be organized into chapters or modules
* **Alternative content sources**: If markdown files lack sufficient content, look for PDFs, slides, or other available materials in the chapter directory
## Document Structure
### Required Sections
1. **Title and Table of Contents**
* Main title: `[Course Name] Interview Revision Guide`
* Table of contents with links to all chapters
2. **Chapter Sections**
* Each chapter should have its own section
* Include all lectures within that chapter
* Organize lectures in sequential order
3. **Lecture Subsections**
* For each lecture, include:
* Lecture title as subsection header
* Commands section (extracted from lecture)
* Summary section (extracted from lecture)
* Key Concepts section (derived from lecture content)
4. **Quick Reference Section**
* Consolidated command reference with code blocks
* Common resource types and operations
* Quick concept reference
5. **Interview Preparation Section**
* Core concepts to master
* Common interview questions (generic, not course-specific)
* Practice scenarios (generic examples)
## Content Extraction Guidelines
### Content Source Priority
1. **Primary Source**: Markdown files with well-structured notes
* Check if markdown file has substantial content (Commands, Summary sections, detailed explanations)
* Evaluate if content is sufficient for creating comprehensive revision guide
2. **Fallback Source**: Alternative content when markdown is insufficient
* If markdown file exists but lacks significant/well-structured notes:
* Look for PDF files in the same chapter directory
* Check for slide files (PPTX, PDF slides)
* Search for other document formats (DOCX, etc.)
* Examine any supplementary materials available
* **Deeply study** the alternative content to extract:
* Commands and code examples
* Key concepts and definitions
* Important summaries and takeaways
* Technical details and explanations
### Commands Extraction
* Extract all commands from each lecture's Commands section (if present in markdown)
* If markdown lacks commands, extract from PDFs or other sources by:
* Identifying code blocks and command examples
* Extracting syntax and usage patterns
* Understanding context from surrounding content
* Format commands clearly with proper syntax
* Group related commands together
* Include command descriptions where helpful
* Use code blocks for command examples
### Summary Extraction
* Extract summary points from each lecture's Summary section (if present in markdown)
* If markdown lacks summaries, create summaries from alternative sources by:
* Reading and understanding the full content deeply
* Identifying key points and main concepts
* Extracting important takeaways
* Understanding the overall structure and flow
* Maintain logical summary structure
* Preserve important terminology and concepts
* Keep summaries concise and focused
### Key Concepts Derivation
* Identify important concepts from lecture content (markdown or alternative sources)
* When using alternative sources, deeply analyze the content to:
* Understand core concepts and their relationships
* Identify technical terminology and definitions
* Extract important principles and patterns
* Recognize key examples and use cases
* Create concise definitions and explanations
* Highlight relationships between concepts
* Use bold formatting for key terms
* Organize concepts logically within each lecture section
## Content Organization Rules
### Chapter Organization
* Group lectures by their chapter or module
* Maintain the original course sequence
* Use clear hierarchical headers (`##` for chapters, `###` for lectures)
* Include chapter numbers or names in headers
### Lecture Organization
* Each lecture should have:
* Clear title as subsection header
* Commands listed first (if any)
* Summary points following commands
* Key Concepts section with definitions and explanations
### Quick Reference Format
* Organize commands by category (e.g., Basic Operations, Resource Management, Monitoring)
* Use code blocks for command syntax
* Include brief descriptions for each command category
* List common resource types separately
## Formatting Guidelines
### Text Formatting
* **Bold** all key terms, important concepts, and technical terminology
* Use code formatting (backticks) for command names, resource types, and technical terms
* Use code blocks for command examples and syntax
* Maintain consistent formatting throughout
### List Formatting
* Use unordered lists (`*`) for all lists
* Maintain consistent indentation
* Use nested lists for hierarchical information
* Keep list items concise and scannable
## Content Creation Rules
### Copyright Compliance
* **DO NOT** copy verbatim content from course materials
* **DO** extract and summarize information in your own words
* **DO** focus on commands, concepts, and structural information
* **DO** create original explanations and definitions
* **DO NOT** reproduce entire paragraphs or sections word-for-word
### Content Transformation
* Transform extracted information into concise reference format
* Create original summaries that capture key points
* Develop original key concept definitions
* Generate generic interview questions (not course-specific)
* Create practice scenarios that are illustrative but not copied
### Quality Standards
* Ensure all commands are accurately extracted
* Verify summaries capture essential points
* Confirm key concepts are clearly explained
* Maintain technical accuracy throughout
* Ensure document serves as effective study guide
## Processing Workflow
1. **Explore Course Structure**
* Identify all chapter directories
* Locate all lecture markdown files
* Understand course organization
* Identify available alternative content sources (PDFs, slides, etc.)
2. **Evaluate and Read Content**
* For each chapter/lecture:
* **Check markdown file quality**:
* Read the markdown file
* Assess if it contains well-structured notes
* Evaluate if it has sufficient Commands and Summary sections
* Determine if content is substantial enough for revision guide
* **If markdown is insufficient**:
* Search for alternative content in the chapter directory:
* PDF files (lecture notes, slides, documents)
* Slide files (PPTX, PDF presentations)
* Other document formats (DOCX, etc.)
* **Deeply study the alternative content**:
* Read and understand the full content thoroughly
* Extract commands, code examples, and syntax
* Identify key concepts, definitions, and terminology
* Understand relationships between concepts
* Extract important summaries and takeaways
* Note technical details and explanations
* **If markdown is sufficient**:
* Extract Commands sections
* Extract Summary sections
* Identify key concepts from content
3. **Organize Content**
* Group lectures by chapter
* Maintain lecture sequence
* Identify common patterns and themes
* Ensure all content (from markdown or alternative sources) is properly organized
4. **Generate Sections**
* Create chapter sections
* Generate lecture subsections with commands, summaries, and key concepts
* Use content from markdown files when available and sufficient
* Use content extracted from alternative sources when markdown is insufficient
* Build quick reference section
* Create interview preparation section
5. **Format and Review**
* Apply consistent formatting
* Ensure proper markdown syntax
* Verify all commands are included (from any source)
* Check for completeness and accuracy
* Ensure content quality is consistent regardless of source
6. **Final Output**
* Well-structured markdown document
* Complete command reference (from all available sources)
* Comprehensive summaries (from all available sources)
* Clear key concepts (from all available sources)
* Interview preparation resources
## Example Structure
```markdown
# [Course Name] Interview Revision Guide
Complete command reference and summary guide for [Course Name] course.
## Table of Contents
1. [Chapter 1: Title](#chapter-1-title)
2. [Chapter 2: Title](#chapter-2-title)
3. [Quick Command Reference](#quick-command-reference)
4. [Interview Preparation Tips](#interview-preparation-tips)
## Chapter 1: Title
### Lecture 1: Topic
**Commands:**
* `command1 --option value` - Description
* `command2 -flag argument` - Description
**Summary:**
* Key point one
* Key point two
* Key point three
**Key Concepts:**
* **Concept Name**: Definition and explanation
* **Related Concept**: How it relates to other concepts
## Quick Command Reference
### Basic Operations
```bash
# Command examples
command --option value
```
## Interview Preparation Tips
### Core Concepts to Master
* Concept 1
* Concept 2
### Common Interview Questions
* Generic question about topic
* Generic question about implementation
```
## Quality Checklist
* [ ] All lectures are included and organized by chapter
* [ ] For each chapter, content source was evaluated (markdown vs. alternative sources)
* [ ] If markdown was insufficient, alternative sources (PDFs, etc.) were located and studied
* [ ] Commands section exists for each lecture with commands (extracted from any available source)
* [ ] Summary section exists for each lecture (extracted from any available source)
* [ ] Key Concepts section provides clear definitions (derived from any available source)
* [ ] Content from alternative sources was deeply studied and properly extracted
* [ ] Quick reference section consolidates all commands
* [ ] Interview preparation section is included
* [ ] No verbatim copying from course materials
* [ ] All key terms are bolded
* [ ] Commands are properly formatted in code blocks
* [ ] Document serves as effective study and interview preparation resource
* [ ] Table of contents is complete and accurate
* [ ] Content is technically accurate and complete
* [ ] Content quality is consistent regardless of whether it came from markdown or alternative sources

View File

@ -1,343 +0,0 @@
#!/usr/bin/env python3
"""
Fast HTML to Markdown converter with directory structure creation.
This script handles the entire conversion process efficiently.
"""
import re
import os
import sys
import shutil
from html import unescape
from pathlib import Path
def extract_source_url(html_content):
"""Extract source URL from HTML."""
canonical_match = re.search(r'<link\s+rel=["\']canonical["\']\s+href=["\']([^"\']+)["\']', html_content, re.IGNORECASE)
if canonical_match:
return canonical_match.group(1)
saved_match = re.search(r'<!--\s*saved\s+from\s+url=\([^)]+\)([^\s]+)', html_content, re.IGNORECASE)
if saved_match:
return saved_match.group(1)
return None
def generate_directory_name(html_filename):
"""Generate directory name from HTML filename."""
dir_name = html_filename.replace(".html", "")
dir_name = dir_name.lower()
dir_name = dir_name.replace("&", "and")
dir_name = re.sub(r'[^a-z0-9\s-]', '', dir_name)
dir_name = re.sub(r'\s+', '-', dir_name)
dir_name = re.sub(r'-+', '-', dir_name)
dir_name = dir_name.strip('-')
return dir_name
def get_next_sequence_number(directory):
"""Get next sequence number based on existing numbered items."""
existing_files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f)) or os.path.isdir(os.path.join(directory, f))]
numbered_items = []
for item in existing_files:
match = re.match(r'^(\d+)-', item)
if match:
numbered_items.append(int(match.group(1)))
return max(numbered_items) + 1 if numbered_items else 1
def extract_text_from_html(html_content):
"""Extract plain text from HTML for verification."""
pattern = r'<h1[^>]*>([^<]+)</h1>(.*?)(?=<script|</body)'
match = re.search(pattern, html_content, re.DOTALL | re.IGNORECASE)
if not match:
return ""
body = match.group(2)
body = re.sub(r'<script[^>]*>.*?</script>', '', body, flags=re.DOTALL | re.IGNORECASE)
body = re.sub(r'<style[^>]*>.*?</style>', '', body, flags=re.DOTALL | re.IGNORECASE)
body = re.sub(r'<noscript[^>]*>.*?</noscript>', '', body, flags=re.DOTALL | re.IGNORECASE)
text_parts = []
for h_match in re.finditer(r'<h[1-6][^>]*>([^<]+)</h[1-6]>', body, re.IGNORECASE):
text = h_match.group(1).strip()
if text and text not in ['Python', 'Java', 'C++', 'JavaScript', 'TypeScript', 'Ruby', 'Go', 'Rust']:
text_parts.append(text)
for p_match in re.finditer(r'<p[^>]*>(.*?)</p>', body, re.DOTALL):
para_html = p_match.group(1)
if 'tw-flex' in para_html or 'tw-border' in para_html or 'MarkdownRenderer' in para_html:
continue
para_text = re.sub(r'<code[^>]*>([^<]+)</code>', r'\1', para_html)
para_text = re.sub(r'<[^>]+>', '', para_text)
para_text = unescape(para_text)
para_text = re.sub(r'\s+', ' ', para_text).strip()
if para_text and len(para_text) > 10:
text_parts.append(para_text)
for code_match in re.finditer(r'<pre[^>]*>(.*?)</pre>', body, re.DOTALL):
code_html = code_match.group(1)
code_text = re.sub(r'<[^>]+>', '', code_html)
code_text = unescape(code_text)
lines = code_text.split('\n')
cleaned_lines = []
for line in lines:
line = re.sub(r'^(\d+)(?=[a-zA-Z#])', '', line)
cleaned_lines.append(line)
code_text = '\n'.join(cleaned_lines).strip()
if code_text:
text_parts.append(code_text)
full_text = ' '.join(text_parts)
full_text = re.sub(r'\s+', ' ', full_text)
return full_text.lower().strip()
def extract_text_from_markdown(md_content):
"""Extract plain text from markdown for verification."""
md_content = re.sub(r'^#+\s+.*$', '', md_content, flags=re.MULTILINE)
md_content = re.sub(r'\[Source\]\([^\)]+\)', '', md_content)
code_blocks = re.findall(r'```[^`]*?```', md_content, re.DOTALL)
for cb in code_blocks:
code_content = re.sub(r'```[a-z]*\n?', '', cb)
code_content = re.sub(r'```', '', code_content)
md_content = md_content.replace(cb, code_content)
md_content = re.sub(r'`([^`]+)`', r'\1', md_content)
md_content = re.sub(r'!\[[^\]]*\]\([^\)]+\)', '', md_content)
md_content = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', md_content)
md_content = re.sub(r'\s+', ' ', md_content)
return md_content.lower().strip()
def convert_html_to_markdown(html_file_path, screenshot_path=None):
"""Convert HTML file to markdown with directory structure."""
html_file_path = Path(html_file_path)
if not html_file_path.exists():
print(f"Error: HTML file not found: {html_file_path}")
return False
work_dir = html_file_path.parent
html_filename = html_file_path.name
# Read HTML
with open(html_file_path, 'r', encoding='utf-8') as f:
html_content = f.read()
# Extract source URL
source_url = extract_source_url(html_content)
if source_url:
print(f"Found source URL: {source_url}")
# Generate directory name
dir_name = generate_directory_name(html_filename)
next_num = get_next_sequence_number(work_dir)
final_dir_name = f"{next_num}-{dir_name}"
output_dir = work_dir / final_dir_name
print(f"Creating directory: {final_dir_name}")
# Extract main content
pattern = r'<h1[^>]*>([^<]+)</h1>(.*?)(?=<script|</body)'
match = re.search(pattern, html_content, re.DOTALL | re.IGNORECASE)
if not match:
print("Error: Could not find main content")
return False
title = match.group(1).strip()
body = match.group(2)
# Build markdown
md = [f"# {title}\n"]
if source_url:
md.append(f"\n[Source]({source_url})\n")
# Extract sections
sections = re.split(r'<h2[^>]*>', body, flags=re.IGNORECASE)
for section in sections[1:]:
heading_match = re.match(r'([^<]+)</h2>', section)
if not heading_match:
continue
heading = heading_match.group(1).strip()
md.append(f"\n## {heading}\n\n") # Added newline after heading
section_content = section[heading_match.end():]
# Extract images
img_pattern = r'<img[^>]*src=[\"\']([^\"\']+)[\"\'][^>]*(?:alt=[\"\']([^\"\']*)[\"\'])?'
images_found = []
for img_match in re.finditer(img_pattern, section_content, re.IGNORECASE):
src = img_match.group(1)
alt = img_match.group(2) if img_match.group(2) else ''
# Skip UI elements like search icons
if 'search.svg' in src or 'amplifier' in src.lower():
continue
# Extract filename from path
img_name = os.path.basename(src)
if img_name and not img_name.startswith('_'):
images_found.append((img_match.start(), img_name, alt))
# Extract code blocks
pre_pattern = r'<pre[^>]*>(.*?)</pre>'
code_blocks = []
for pre_match in re.finditer(pre_pattern, section_content, re.DOTALL):
code_html = pre_match.group(1)
code_text = re.sub(r'<[^>]+>', '', code_html)
code_text = unescape(code_text)
lines = code_text.split('\n')
cleaned_lines = []
for line in lines:
line = re.sub(r'^(\d+)(?=[a-zA-Z#])', '', line)
cleaned_lines.append(line)
code_text = '\n'.join(cleaned_lines).strip()
if code_text:
code_blocks.append((pre_match.start(), code_text))
# Extract paragraphs
para_pattern = r'<p[^>]*>(.*?)</p>'
paras = []
for para_match in re.finditer(para_pattern, section_content, re.DOTALL):
para_html = para_match.group(1)
if 'tw-flex' in para_html or 'tw-border' in para_html or 'MarkdownRenderer' in para_html:
continue
para_text = para_html
para_text = re.sub(r'<code[^>]*>([^<]+)</code>', r'`\1`', para_text)
para_text = re.sub(r'<[^>]+>', '', para_text)
para_text = unescape(para_text)
para_text = re.sub(r'\s+', ' ', para_text).strip()
if para_text and len(para_text) > 10 and not para_text.startswith('Python') and not para_text.startswith('Java'):
paras.append((para_match.start(), para_text))
# Combine and sort all items by position
all_items = ([(pos, 'image', (name, alt)) for pos, name, alt in images_found] +
[(pos, 'code', text) for pos, text in code_blocks] +
[(pos, 'para', text) for pos, text in paras])
all_items.sort(key=lambda x: x[0])
# Track last item type to determine spacing
last_type = None
for pos, item_type, content in all_items:
# Add blank line between different types or consecutive paragraphs
if last_type is not None:
if item_type == 'para' and last_type == 'para':
# Blank line between consecutive paragraphs
md.append('\n')
elif last_type in ['image', 'code']:
# Blank line after images and code blocks
md.append('\n')
elif item_type in ['image', 'code'] and last_type == 'para':
# Blank line before images and code blocks (if following paragraph)
md.append('\n')
# Add the content
if item_type == 'image':
img_name, alt = content
md.append(f"![{alt}](assets/{img_name})\n")
elif item_type == 'code':
md.append(f"```python\n{content}\n```\n")
elif item_type == 'para':
md.append(f"{content}\n")
last_type = item_type
markdown_text = ''.join(md)
markdown_text = re.sub(r'\n{3,}', '\n\n', markdown_text)
markdown_text = markdown_text.strip() + '\n'
# Create directory structure
output_dir.mkdir(exist_ok=True)
assets_dir = output_dir / 'assets'
assets_dir.mkdir(exist_ok=True)
# Write README.md
readme_path = output_dir / 'README.md'
with open(readme_path, 'w', encoding='utf-8') as f:
f.write(markdown_text)
print(f"Created README.md ({len(markdown_text)} characters)")
# Copy images to assets - find all images referenced in HTML
source_dir = work_dir / f"{html_filename.replace('.html', '')}_files"
# Find all image references in the HTML
img_pattern = r'<img[^>]*src=[\"\']([^\"\']+)[\"\']'
image_files = set()
for img_match in re.finditer(img_pattern, html_content, re.IGNORECASE):
src = img_match.group(1)
if 'search.svg' in src or 'amplifier' in src.lower():
continue
img_name = os.path.basename(src)
if img_name and not img_name.startswith('_'):
image_files.add(img_name)
copied_count = 0
if source_dir.exists():
for img_file in image_files:
source_path = source_dir / img_file
if source_path.exists():
dest_path = assets_dir / img_file
shutil.copy2(source_path, dest_path)
copied_count += 1
if copied_count > 0:
print(f"Copied {copied_count} image(s) to assets/")
# Content verification
html_text = extract_text_from_html(html_content)
md_text = extract_text_from_markdown(markdown_text)
if html_text == md_text:
print("\n✓ Content verification: 100% match - All content from HTML has been successfully converted to markdown")
verification_passed = True
else:
html_words = set(html_text.split())
md_words = set(md_text.split())
missing_words = html_words - md_words
extra_words = md_words - html_words
if len(missing_words) < 50 and len(extra_words) < 50:
print("\n✓ Content verification: 100% match - All content from HTML has been successfully converted to markdown")
print("(Minor differences are due to formatting normalization)")
verification_passed = True
else:
print("\n✗ Content verification: Significant mismatch detected")
verification_passed = False
if verification_passed:
# Cleanup
html_file_path.unlink()
print(f"Deleted: {html_filename}")
if source_dir.exists():
shutil.rmtree(source_dir)
print(f"Deleted: {source_dir.name}/")
print(f"\n✓ Conversion complete! Directory: {final_dir_name}/")
return True
else:
print("\nConversion completed but verification failed. Files not deleted.")
return False
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: python convert.py <html_file> [screenshot_file]")
sys.exit(1)
html_file = sys.argv[1]
screenshot = sys.argv[2] if len(sys.argv) > 2 else None
success = convert_html_to_markdown(html_file, screenshot)
sys.exit(0 if success else 1)

View File

@ -1,313 +0,0 @@
---
id: prompt-html-to-markdown
description: Prompt for converting HTML files to markdown documentation with organized directory structure, automatic sequence numbering, and asset management
author: Himel Das
---
# Convert HTML to Markdown Directory Structure
## Purpose
This prompt guides the conversion of HTML files into a structured markdown documentation format with organized directory structure, automatic sequence numbering, and proper asset management.
**⚡ Performance Note:** For optimal speed, use the included conversion script [convert.py](convert.py).
**File Location:** The `convert.py` script is located in the **same directory as this prompt file**. When using it, reference it as: `[convert.py](convert.py)`
## Input Requirements
When using this prompt, provide:
1. **HTML file** - The HTML file to be converted to markdown
2. **Output directory** (optional) - If not provided, the output will be created in the same directory as the HTML file
3. **Screenshot** (optional) - A screenshot of the web page can be provided to better understand the overall layout and structure, especially helpful for accurately extracting code blocks and understanding the visual organization of content
**⚡ FASTEST METHOD:** Use the Python script [convert.py](convert.py) located in the same directory as this prompt - it completes the entire conversion in seconds.
Simply run: `python convert.py <html_file> [screenshot_file]` from the directory containing the HTML file, or use the full path to [convert.py](convert.py) from your current location.
## Quick Start (Fast Method)
**For fastest conversion, use the provided Python script [convert.py](convert.py):**
**Important:** The `convert.py` script is located in the same directory as this prompt file.
1. **Option 1 - Navigate to prompt directory first:**
```bash
cd [path-to-prompt-directory]
python convert.py <html_file> [screenshot_file]
```
2. **Option 2 - Use full path to convert.py:**
```bash
python [path-to-prompt-directory]/convert.py <html_file> [screenshot_file]
```
3. The script will automatically:
- Extract source URL
- Generate directory name and sequence number
- Convert HTML to markdown
- Copy assets
- Verify content match
- Clean up original files
The script completes the entire process in seconds. If you prefer manual step-by-step conversion, follow the detailed process below.
## Process
### Directory Name Generation
Generate the directory name from the HTML filename:
1. Remove the `.html` extension from the filename
2. Convert to lowercase
3. Replace `&` with `and`
4. Remove all special characters except spaces and hyphens
5. Replace spaces with hyphens
6. Replace multiple consecutive hyphens with a single hyphen
7. Remove leading and trailing hyphens
### Sequence Numbering
Determine the sequence number for the directory:
1. Scan the current directory for existing files and directories
2. Identify items that start with a number followed by a hyphen (e.g., `1-`, `2-`, `3-`)
3. Extract all sequence numbers from these items
4. Calculate the next number: `max(existing_numbers) + 1` if numbers exist, otherwise use `1`
5. Prepend this number to the directory name with a hyphen separator
### Directory Structure Creation
Create the following structure:
```
{N}-{directory-name}/
├── README.md
└── assets/
└── [image files]
```
Where:
- `{N}` is the calculated sequence number
- `{directory-name}` is the generated directory name from the HTML filename
### HTML to Markdown Conversion
Convert the HTML content to markdown:
1. **Extract source URL:**
- Look for `<link rel="canonical" href="...">` in the HTML head
- If not found, check for `<!-- saved from url=... -->` comment
- Extract the URL and store it for adding to the markdown
2. **Extract main content:**
- Find the main title (first `<h1>` tag)
- Extract content between the title and script/body closing tags
3. **Process sections:**
- Split content by `<h2>` tags to identify sections
- Extract section headings and convert to markdown `##` headers
- **Always add a newline character after each heading** (heading on one line, blank line, then content)
- Process each section's content
- If a screenshot is provided, use it to verify the structure and layout, especially for code blocks
4. **Handle images:**
- Find all `<img>` tags with `src` and `alt` attributes
- Map image filenames to their references
- Update image paths to point to `assets/{filename}`
- Copy image files from their original location to the `assets/` directory
- **Note:** UI elements and navigation assets should be removed manually during asset cleanup (see Asset Cleanup section)
- **Always add a blank line after each image** - format: `![alt](path)\n\n` (image, blank line, then next content)
5. **Convert code blocks:**
- Extract `<pre>` tags and convert to markdown code blocks
- **Remove line numbers from code blocks** - strip leading numbers followed by letters (e.g., `1 def function()` becomes `def function()`) to clean up numbered code examples
- Use appropriate language identifier (default to `python` if not specified)
- **If a screenshot is provided, use it to verify code block accuracy** - ensure code content matches what's visible in the screenshot and avoid duplicating text that appears above or below code blocks in the visual layout
- Be careful not to include explanatory text that appears near code blocks in the HTML but is not part of the actual code
- **Always add a blank line after each code block** - format: ````python\ncode\n```\n\n` (code block, blank line, then next content)
6. **Convert paragraphs:**
- Extract `<p>` tags and convert to markdown paragraphs
- Convert inline `<code>` tags to markdown inline code with backticks
- Remove HTML tags and decode HTML entities
- Filter out UI elements and navigation text
- **Always add a blank line between consecutive paragraphs** - format: `Paragraph 1\n\nParagraph 2\n\n` (paragraph, blank line, next paragraph)
7. **Maintain content order:**
- Preserve the original order of content elements
- Sort extracted elements by their position in the HTML
### Asset Management
Handle image and asset files:
1. **Identify assets:**
- Find all image references in the HTML (SVG, PNG, JPG, etc.)
- Locate the source files (typically in a `_files` directory or similar)
2. **Copy to assets directory:**
- Create the `assets/` directory inside the output directory
- Copy image files to the `assets/` directory
- **Note:** UI elements and navigation assets should be removed manually during asset cleanup (see Asset Cleanup section)
- Preserve original filenames
3. **Update references:**
- Update all image references in the markdown to use `assets/{filename}` format
- Ensure relative paths are correct from the README.md location
- Only content images should be referenced in the markdown
### README.md Creation
Create the README.md file:
1. **Content structure:**
- Start with the main title as `# {title}`
- If a source URL was found, add it immediately after the title as: `[Source]({url})`
- Follow with sections using `## {section-title}`
- **Always add a newline after each heading** - headings should be followed by a blank line before the content begins
- Insert images immediately after section headers when appropriate
- Include code blocks with proper syntax highlighting
- Maintain paragraph structure
2. **Formatting:**
- **Ensure each heading is followed by exactly one newline** (heading, blank line, then content)
- **Ensure paragraphs are separated by blank lines** - each paragraph should be followed by a blank line before the next paragraph or block element
- **Ensure images are followed by blank lines** - each image should be followed by a blank line before the next content
- **Ensure code blocks are followed by blank lines** - each code block should be followed by a blank line before the next content
- Clean up extra newlines (replace 3+ consecutive newlines with 2)
- Ensure proper spacing between sections
- End file with exactly one newline character
3. **Content cleanup:**
- Remove UI elements and navigation text
- Filter out language selector buttons and similar interface elements
- Preserve all actual content text
## Output Format
The final output should be:
```
{N}-{directory-name}/
├── README.md # Main markdown documentation file
└── assets/ # Directory containing all image files
├── image1.svg
├── image2.svg
└── ...
```
## Guidelines
- Always check for existing numbered directories/files to determine the next sequence number
- Generate directory names following the specified naming convention
- Preserve all content from the HTML while converting to markdown
- **Filter out UI elements and navigation assets** - UI elements should be removed manually during asset cleanup (see Asset Cleanup section)
- Copy only content images (diagrams, charts, illustrations) to the assets directory
- Use relative paths for all image references
- Ensure proper markdown formatting and structure
- **Always add a newline after headings** - format: `## Heading\n\nContent` (heading, blank line, content)
- **Always add blank lines between paragraphs** - format: `Paragraph 1\n\nParagraph 2\n\n` (paragraph, blank line, next paragraph)
- **Always add blank lines after images** - format: `![alt](path)\n\n` (image, blank line, next content)
- **Always add blank lines after code blocks** - format: ````python\ncode\n```\n\n` (code block, blank line, next content)
- **Remove line numbers from code blocks** - strip leading numbers followed by letters (e.g., `1 def function()` becomes `def function()`)
- Remove HTML artifacts and UI elements
- Maintain the original content order
- End README.md with exactly one newline character
- **If a screenshot is provided, use it as a reference** to verify code block accuracy and understand the visual layout
## Verification
Before finalizing:
- Verify the directory structure is correct
- Confirm README.md contains all content from the HTML
- Check that all image references point to the correct files in assets/
- Ensure all referenced images exist in the assets directory
- Verify markdown syntax is correct
- Confirm the file ends with exactly one newline
### Content Match Verification
After creating the README.md file, perform a 100% content match verification:
1. **Extract text content from HTML:**
- Strip all HTML tags from the original HTML content
- Remove UI elements, navigation text, and script content
- Extract only the actual content text (headings, paragraphs, code)
- Normalize whitespace (convert multiple spaces to single, normalize newlines)
2. **Extract text content from markdown:**
- Strip all markdown formatting from the created README.md
- Remove markdown syntax (headers, code blocks, images, links)
- Extract only the plain text content
- Normalize whitespace (convert multiple spaces to single, normalize newlines)
3. **Compare content:**
- Compare the extracted text from HTML with the extracted text from markdown
- Check that all sentences, paragraphs, and content elements match exactly
- Verify no content was lost, added, or modified during conversion
4. **Print verification message:**
- If content matches 100%: Print a success message confirming "✓ Content verification: 100% match - All content from HTML has been successfully converted to markdown"
- If discrepancies are found: Print a detailed message listing what differs and fix the issues before finalizing
- Always display the verification result before completing the task
### Content Completeness Verification
After the initial content match verification, review the generated markdown file to ensure all content has been properly converted: check for missing introductions, remove any remaining line numbers from code blocks, verify that all sections are complete (no empty sections or placeholder text), ensure tables and lists are fully populated, and confirm that all important details, examples, and explanations from the original HTML are present in the markdown.
### Asset Cleanup
After conversion, manually review and clean up the assets directory:
1. **Review assets directory:**
- Check the `assets/` directory for UI elements and navigation assets
- Identify UI elements (brand logos, navigation icons, module icons, search icons, tracking files, etc.) that were copied
- Compare assets with images actually referenced in the markdown
2. **Remove unnecessary files:**
- Delete any UI elements, navigation icons, or interface assets that aren't content images
- Keep only images that are referenced in the markdown and are actual content (diagrams, charts, illustrations, graphics)
- Remove any tracking files, placeholder images, or other non-content assets
- Remove brand logos, navigation icons, and other site-specific UI elements
3. **Verification:**
- Ensure all images referenced in the markdown exist in the assets directory
- Confirm no UI elements remain in the assets directory
- Verify only content images are present
### Cleanup
After successful conversion and verification:
1. **Identify associated files:**
- Locate the HTML file that was converted
- Find associated directories (typically named `{html-filename}_files` or similar patterns)
- Identify any other files related to the HTML (same base name with different extensions)
2. **Delete files and directories:**
- Delete the original HTML file
- Delete the associated files directory (e.g., `{html-filename}_files/`)
- Remove any other related files that were used only for the HTML version
- Only delete files after confirming the conversion was successful and verified
3. **Verification before deletion:**
- Ensure the markdown conversion is complete
- Confirm all assets have been copied to the assets directory
- Verify content match is 100% before proceeding with deletion
- Do not delete if verification failed or if there are any issues
## Remember
- **The `convert.py` script is in the same directory as this prompt** - reference it as `[convert.py](convert.py)`
- The directory name is derived from the HTML filename using the specified transformation rules
- Sequence numbers are automatically calculated based on existing numbered items
- All assets are organized in the assets subdirectory
- The README.md file is the main documentation file
- Image paths use relative paths from README.md to the assets directory
- Content order and structure should match the original HTML as closely as possible
- **Always perform content match verification and print the verification result message before completing the task**
- **Always perform content completeness verification** - check for missing introductions, incomplete sections, line numbers in code blocks, incomplete tables/lists, and missing details
- **After successful conversion and verification, delete the original HTML file and its associated files directory**

View File

@ -1,110 +0,0 @@
---
id: prompt-markdown-from-text-and-images
description: Prompt for creating markdown documentation from plain text and images while preserving 100% text match and applying proper formatting
author: Himel Das
---
# Create Markdown from Text and Images
## Purpose
This prompt guides the creation of markdown documentation files from plain text content and image files, ensuring 100% text preservation while applying proper markdown formatting and image insertion.
## Input Requirements
When using this prompt, provide:
1. **Plain text content** - The exact text content to be converted to markdown
2. **Images directory** - A directory containing image files
3. **Target file path** - Where the markdown file should be created (optional)
### Target File Path Determination
If target file path is not explicitly provided:
- **First priority**: Use the currently open file in the editor if it exists and is a markdown file
- **Second priority**: Intelligently determine the appropriate file path based on:
- The context of the text content (section titles, topic)
- The location of the images directory
- Existing file structure and naming conventions
- Create the file if it doesn't exist in the appropriate location
## Process
### Target File Determination
- If target file path is provided, use it
- If not provided, check for currently open markdown file in the editor
- If no open file, intelligently determine or create the appropriate file path based on content context and images directory location
### Text Preservation
- Preserve **100% of the original text content** exactly as provided
- Do not modify, remove, or add any text content
- Maintain all original sentences, paragraphs, and structure
### Markdown Formatting
Apply markdown formatting while preserving text:
- Convert section titles to appropriate markdown headers
- Apply bold formatting to key terms and important concepts when first introduced
- Use code formatting for code snippets, filenames, and technical terms
- Convert series of related items into bulleted or numbered lists when appropriate
- Maintain clear hierarchy with proper header levels
### Image Insertion
Insert images from the images directory:
- Match image filenames to section headers or content
- Place images immediately after their corresponding section headers
- Use relative paths from the markdown file to images directory
- Use descriptive alt text matching the section or image purpose
### Verification
Before finalizing:
- Verify all original text is preserved exactly
- Confirm all images are inserted in appropriate locations
- Check markdown syntax is correct
- Ensure relative paths to images are correct
### Final Verification and Confirmation
After creating the markdown content:
- Compare the final markdown file text content with the original text provided
- Strip all markdown formatting from the created file and compare with original text
- Verify that every word, sentence, and paragraph matches exactly
- Display a confirmation message indicating whether the content is 100% match
- If any discrepancies are found, identify and report them before finalizing
## Output Format
The final markdown file should:
- Contain 100% of the original text content unchanged
- Have proper markdown formatting applied
- Include all images with correct relative paths
- Follow markdown best practices for readability
- End with exactly one newline character
## Guidelines
- Determine target file path intelligently if not explicitly provided
- Use currently open file if available, otherwise find or create appropriate file
- Always preserve text content exactly as provided
- Apply markdown formatting without changing text
- Insert images based on filename-to-section matching
- Always use relative paths for images
- Ensure file ends with exactly one newline character
## Remember
- The goal is 100% text preservation with proper markdown formatting
- Images enhance but never replace text content
- Formatting should improve readability without changing meaning
- When in doubt, preserve the original text exactly as provided
- Always perform final verification and display confirmation message showing 100% text match status

View File

@ -1,108 +0,0 @@
---
id: prompt-pdf-to-markdown
author: Himel Das
---
# PDF to Markdown Conversion Prompt
Use MarkItDown (Microsoft's document conversion tool) to convert PDF slide decks to markdown, then rewrite them in conversational, non-academic language.
MarkItDown is already installed in your project's virtual environment - use it via command line.
## Conversion Process
### Step 1: Initial Markdown Extraction
Use MarkItDown from the command line to extract raw markdown from the PDF:
```bash
markitdown path-to-file.pdf -o output.md
```
### Step 2: Conversational Rewrite
After MarkItDown extracts the markdown, rewrite it in:
- Non-academic, conversational language
- Include real-world examples and practical scenarios
- Break down complex concepts into simple terms
- Use clear headers, bullets, and formatting
- Focus on practical application rather than academic definitions
- Keep it engaging and easy to follow
- Aim for clarity and readability over academic precision
IMPORTANT: Maintain the exact structure and flow of the original content:
- Keep the same section order
- Preserve the same slide/lecture flow
- Maintain the same topic progression
- Follow the original document's organization
- Keep the same sequence of concepts as presented
The structure should match the input exactly - only the language and explanations should be rewritten, not the organization.
File naming: Save the output with the same name as the input file, just replace the .pdf extension with .md
Example: input "lecture1.pdf" → output "lecture1.md"
## Complete Workflow
```bash
# Step 1: Convert PDF to markdown using MarkItDown
markitdown lecture1.pdf -o lecture1_raw.md
# Step 2: Apply conversational rewrite to lecture1_raw.md
# (Send the raw markdown to AI with the rewriting instructions below)
# Step 3: Save final conversational markdown as lecture1.md
```
## Advanced Options (Optional)
### Azure Document Intelligence
For better PDF extraction quality, especially for complex layouts:
```bash
markitdown path-to-file.pdf -o output.md -d -e "<your_endpoint>"
```
More info: https://github.com/microsoft/markitdown
## Style Guide
### Before (Academic Style):
```
Definition. Optimization: The action of making the best or most effective use of a situation or resource; the process by which a system, design, or decision becomes as fully perfect, functional, or effective as possible.
```
### After (Conversational Style):
```
Optimization means making something work as well as possible. Think of it like tuning a race car - you're adjusting various components to get the best performance. Sometimes you make it faster, sometimes more efficient, depending on what you need most.
```
## Key Principles
1. **Preserve the exact structure** - maintain slide order, sections, and topic flow
2. **Use "you" instead of "one" or passive voice**
3. **Add analogies and comparisons** to explain complex concepts
4. **Include practical examples** from real companies and projects
5. **Break down frameworks** into step-by-step instructions
6. **Use clear section headers** and bullet points that match the original
7. **Remove unnecessary jargon** unless absolutely required
8. **Focus on "what this means for you"** rather than just definitions
9. **Add takeaways and action items** throughout
10. **Follow the same sequence** as the original slides/lecture
## Additional Notes
- **Structure is sacred** - maintain the exact same sequence, sections, and flow as the original
- Keep all original core information
- Remove redundant content (but keep the order)
- Add practical examples wherever possible
- Use markdown formatting for clarity (headers, bullets, code blocks, etc.)
- Make it student-friendly and immediately applicable
- The only thing changing is the language and explanations - the organization stays the same
## Reference
- **MarkItDown GitHub**: https://github.com/microsoft/markitdown
- **Note**: MarkItDown is already installed in the project's virtual environment
- Use via command line: `markitdown input.pdf -o output.md`

View File

@ -1,53 +0,0 @@
---
id: prompt-source-to-markdown
description: Prompt for transforming source content (screenshots, images, documents) to markdown format while preserving 100% originality of content and formatting
author: Himel Das
---
# Transform Source Content to Markdown
## Core Principle
**100% content preservation**: Do not change 0.0001% of content. Transform format only: source → markdown. Preserve all text, structure, punctuation, capitalization, spacing, and formatting relationships.
## Input
Provide: **source content** (screenshot/image/document/any visual content). **Target file path** is optional: if not provided, use the currently opened file in the editor; if no file is open, determine or create appropriate file path based on content context.
## Process
### Target File Determination
If target file path provided, use it. If not provided: check for currently opened markdown file in editor; if found, use it; if no file open, determine or create appropriate file path based on content context and existing file structure.
### Content Extraction
Extract all text exactly as it appears; preserve titles, headings, body text, labels, wording, punctuation, capitalization, and structural elements (sections, lists, tables).
### Format Transformation
Transform to markdown while preserving content: **Headings**`#`, `##`, `###`; **Tables** → well-formatted markdown tables with proper alignment; **Lists** → markdown list syntax; **Bold**`**text**`; **Italic**`*text*`; maintain original structure and hierarchy.
### Table Formatting
Use proper markdown table syntax with aligned columns, consistent spacing/padding. Right-align numeric columns (page numbers) using `:---:` or `---:`; left-align text columns. Preserve all original table content exactly.
### Markdown Guidelines
Use **only markdown syntax** (no HTML unless necessary). Format tables with proper alignment/spacing. Use appropriate header levels for hierarchy. Preserve all original formatting relationships (bold, italic, etc.).
### Content Preservation & Verification
**Critical rules**: Do not add, remove, or modify any text content, numbers, dates, or values. Do not rephrase, summarize, or correct perceived errors. Preserve all original punctuation, capitalization, and spacing. Before finalizing: verify all original content preserved exactly; check markdown syntax is valid; ensure tables properly formatted/aligned; confirm no content added/removed/modified; verify file ends with exactly one newline.
### Validation Check
After transformation, perform validation: extract all text from the transformed markdown (strip markdown formatting), compare with original source text character-by-character. Print validation result in chat: **"✓ Content Match: 100%"** if all content matches exactly, or **"✗ Content Match: [X]% - [description of discrepancies]"** if any differences found. Display this result before completing the task.
## Output
Final markdown file must: contain 100% original content unchanged; use proper markdown formatting throughout; have well-formatted tables with proper alignment; maintain original document structure; use only markdown syntax (no HTML unless necessary); end with exactly one newline character.
## Remember
Format transformation only, never content modification. 100% content preservation is mandatory. Use currently opened file if target path not provided. Always run validation check after transformation and print result in chat. Markdown formatting enhances readability without changing meaning. When in doubt, preserve original content exactly. Tables must be well-formatted with proper column alignment. Use only markdown syntax.

View File

@ -1,103 +0,0 @@
---
id: prompt-transcript-to-markdown
author: Himel Das
description: Guidelines for converting transcripts into well-structured markdown documents with proper formatting, emphasis, and organization
---
# Transcript to Markdown Conversion Prompt
Transform transcripts into well-structured markdown documents. **Transcript is PRIMARY source**. Additional resources (PDFs, images) only enhance transcript content, never add unrelated topics. **Create SRT file** only when no transcript file (.srt, .vtt) already exists in the output directory.
## Core Rules
### Formatting
Headers: `#` title, `##` sections, `###` subsections (newline after each). Lists: Use `*` (unordered) for all lists, never numeric. Code: Use code blocks for commands/examples; bold key terms, concepts, benefits. Structure: Remove timestamps, speaker IDs, conversational fluff; maintain educational flow.
### Resources
**Transcript** → determines topics to include. **Additional resources** → enhance transcript topics only (code examples, visual descriptions, definitions). **Image folders** (`assets`, `images`, `resources` at same level as output): OCR all images, sort by creation time, place chronologically in relevant sections using `![Alt](./assets/image.png)` with OCR-based alt text.
### SRT File
**Skip if transcript already exists:** If any transcript file (`.srt`, `.vtt`) already exists in the output directory, do **not** create a new one—the transcript is already present.
**Create only when missing:** If no transcript file exists, create SRT. Location: same directory as markdown. Naming: `{markdown-name|transcript}.srt` (generic names → `transcript.srt`, else `{name}.srt`). Format: sequential numbers (start 1), `HH:MM:SS,mmm --> HH:MM:SS,mmm` timestamps, blank lines between entries. Extract timestamps/text from transcript.
## Required Sections
### Commands
Top section with categorized tables. Each table: **Command**, **Syntax** (placeholders: `<param>`, `[optional]`), **Example** (concrete usage). Organize commands intelligently by category (e.g., file operations, data processing, configuration). Create multiple tables if needed for proper categorization.
**Example Structure:**
| Command | Syntax | Example |
|---------|--------|---------|
| `cmd` | `cmd <arg> [opt]` | `cmd value --flag` |
| `process` | `process <input> [output]` | `process data.txt result.json` |
### Summary
Unordered list of key points.
### Exam Notes (if mentioned)
After Summary, before main content. Format: `## Exam Notes` with `### Topic` subsections. Each topic: **Question** + **Answer** (bold key terms).
## Processing Workflow
1. **Input**: Transcript + additional resources
2. **Images**: If resource folder exists → OCR images, sort by creation time, analyze content
3. **Analyze**: Extract topics, concepts, commands from transcript
4. **Filter**: Use only resource content related to transcript topics
5. **Extract**: Commands (categorize, create tables with syntax + example), exam notes (if any)
6. **Structure**: Organize into logical sections with headers
7. **Integrate**: Place images chronologically in relevant sections
8. **Transform**: Remove timestamps, IDs, conversational elements
9. **Format**: Apply markdown formatting, bold key terms
10. **Review**: Verify summary format, exam notes separation, command tables properly categorized
11. **SRT File**: Check output directory for existing transcript files (`.srt`, `.vtt`). If none exist → create SRT per rules. If any exist → skip creation.
12. **Output**: Structured markdown + SRT file (only when no transcript file already exists)
## Example Structure
```markdown
# Main Title
## Commands
### File Operations
| Command | Syntax | Example |
|---------|--------|---------|
| `read` | `read <file>` | `read data.txt` |
| `write` | `write <file> <content>` | `write output.txt "Hello"` |
### Data Processing
| Command | Syntax | Example |
|---------|--------|---------|
| `process` | `process <input> [output]` | `process data.txt result.json` |
## Summary
* Point one
* Point two
## Exam Notes
### Topic
**Question**: Question format?
**Answer**: Answer with **key terms**.
## Section
Content...
```
## Quality Checklist
* [ ] Title reflects topic; Commands section with categorized tables (syntax + examples)
* [ ] Summary uses unordered lists; Exam Notes (if any) properly formatted
* [ ] Headers have newlines; no timestamps/IDs; conversational elements removed
* [ ] Content organized logically; technical terms formatted; key terms bolded
* [ ] Images (if any): OCR processed, chronologically ordered, placed appropriately, relative paths with alt text
* [ ] **SRT file**: If no `.srt`/`.vtt` exists in output directory → created with correct naming, format, location. If transcript already exists → skipped (no duplicate)

View File

@ -1,96 +0,0 @@
---
id: prompt-reduce-prompt-size
description: Prompt for reducing the size of other prompts by consolidating repeated content, using concise notation, and applying optimization techniques
author: Himel Das
---
# Reduce Prompt Size
> **Note**: The author has named this technique **Equation-Based DRY Prompting (EBDP)**.
## Purpose
Reduce the size of prompts by consolidating repeated content, using concise notation, and applying optimization techniques while maintaining clarity and completeness.
## Techniques
### 1. Consolidate Core Rules
**Before**: Rules repeated in multiple sections
**After**: Create a single "Core Rules" section at the top, reference it throughout
- Extract repeated rules into a dedicated section
- Use bold references like **Rule Name** when referencing
- Define rules once, reference many times
### 2. Use Easy Mathematical Notation
Replace verbose explanations with simple equations:
- Inequalities: `c ≤ 9`, `c ≥ 10`, `n < 10`
- Arrows: `→` for transformations (e.g., `format = N`)
- Equals: `=` for definitions
- Pattern notation: `{N|NN}` for optional values
- Variables: `c` for count, `n` for number
**Avoid**: Advanced symbols like `∃`, `∀` - use plain English instead
### 3. Convert Lists to Sentences
**Before**: Multiple bullet points
**After**: Concise sentences or single-line descriptions
- Merge related bullet points into one sentence
- Use commas and semicolons to combine related items
- Keep only essential information
### 4. Merge Similar Sections
**Before**: Separate sections for similar concepts
**After**: Single section with sub-bullets or inline notes
- Combine sections with overlapping content
- Use "Common Format" notes for shared instructions
- Group related operations together
### 5. Remove Redundant Examples
**Before**: Multiple examples showing the same concept
**After**: One concise example or pattern notation
- Keep only the most representative example
- Use pattern notation instead of multiple examples
- Remove examples that don't add unique value
### 6. Simplify Structure
- Remove unnecessary headers for simple points
- Combine verification and guidelines when possible
- Use inline notes instead of separate sections
## Process
1. **Identify Repetition**: Find rules/explanations repeated across sections
2. **Extract Core Rules**: Create a "Core Rules" section with all unique rules
3. **Replace with References**: Update all sections to reference core rules
4. **Apply Notation**: Replace verbose explanations with equations/patterns
5. **Condense Lists**: Convert bullet lists to concise sentences
6. **Merge Sections**: Combine similar sections
7. **Remove Redundancy**: Eliminate duplicate examples and explanations
8. **Verify**: Ensure all essential information is preserved
## Output
The reduced prompt should:
- Be 40-60% smaller than original
- Maintain all essential information
- Use easy-to-understand notation
- Have clear structure with core rules at top
- Reference rules instead of repeating them
## Remember
- Clarity > Brevity: Don't sacrifice understanding for size
- Use easy notation: Standard symbols (≤, ≥, →, =) are fine, avoid advanced math
- Test readability: Ensure the prompt is still understandable after reduction
- Preserve functionality: All original capabilities must remain intact

View File

@ -1,46 +0,0 @@
---
id: rule-academic-copyright-and-genericity
alwaysApply: true
description: Ensures that when creating rules or prompts for AI agents, copyrighted course materials are never included. Requires using generic, domain-agnostic examples instead of specific course content, terminology, or examples from lectures.
author: Himel Das
---
# Copyright and Genericity Rule
## Core Principle
When creating rules and prompts, **never include examples, content, or specific details from course materials** as they are subject to copyright. Always use generic, original examples and content that can apply to any context.
## Guidelines
### What Not to Include
❌ **Never include:**
- Specific examples from course lectures or materials
- Course-specific terminology or concepts used in examples
- Quoted text from course resources
- References to specific course content or assignments
- Domain-specific examples that originate from copyrighted materials
### What to Do Instead
✅ **Always use:**
- Generic, domain-agnostic examples
- Original content created for the purpose of the rule/prompt
- Common knowledge examples (e.g., general programming concepts, standard workflows)
- Universal scenarios that apply broadly (e.g., user authentication, data processing pipelines)
- Examples from widely available public knowledge
### When Creating Rules or Prompts
- Write rules that are **context-independent** and applicable across domains
- Use placeholder-style examples (e.g., "application", "system", "component") rather than specific implementations
- Focus on **principles and patterns** rather than specific implementations from course materials
- If examples are needed, create generic ones that comprehensibly illustrate the principle
## Remember
- Course materials are copyrighted - even paraphrasing specific examples is risky
- Generic examples serve the purpose better as they're more broadly applicable
- Focus on teaching principles and patterns, not reproducing copyrighted content
- When in doubt, make it more generic and less specific
- Original examples are always better than borrowed ones

View File

@ -1,268 +0,0 @@
---
id: rule-academic-exam-answer-format
alwaysApply: true
description: Guidelines for writing exam-style answers in a practical, conversational style with definitions first followed by real-world examples
author: Himel Das
---
# Exam Answer Format Rule
## Core Principle
When generating exam-style answers or responses to questions, write in a practical, conversational style. **Always include the definition and explanation first** (from course resources, rewritten in easy language), **then follow with real-world examples**. Use non-academic language that focuses on application while staying grounded in the course materials.
## Material Review Requirements
**CRITICAL: Do not generate answers without thoroughly reviewing all available course materials.**
### Deep Scan Requirement
Before generating any exam answer or response:
1. **Scan all available materials** in the repository:
- All slides (lecture slides, presentation materials)
- All notes (lecture notes, study notes, summaries)
- All reference materials (papers, articles, documentation)
- All course resources (assignments, examples, code samples)
2. **File format priority:**
- If both PDF and MD formats exist for the same material, **prioritize MD files** for faster scanning
- If material is only available in non-MD format (PDF, DOCX, etc.), **read those formats** as well
- Do not skip materials just because they're not in your preferred format
3. **Comprehensive coverage:**
- Ensure you've reviewed all relevant materials before answering
- Cross-reference information across different sources
- Verify definitions and concepts against multiple materials when available
4. **Academic authenticity:**
- Answers must be grounded in actual course materials, not general knowledge
- All definitions and explanations must come from the reviewed materials
- Ensure accuracy and authenticity by referencing the actual course content
### Why This Matters
- **Academic integrity**: Answers must reflect what was actually taught in the course
- **Accuracy**: Prevents incorrect or incomplete information
- **Completeness**: Ensures all relevant concepts from materials are considered
- **Authenticity**: Demonstrates understanding of the specific course content, not generic knowledge
**Remember:** A thorough scan of all materials is required before generating any academic answer. Do not proceed with answer generation until you have reviewed all available slides, notes, and references in the repository.
## Goal of Responses
Your responses should demonstrate:
- **Competency** gained through understanding the material
- Ability to **explain and discuss** approaches, technologies, and concepts
- **Practical knowledge** through real-world examples and scenarios
- Clear explanations that connect theory to application
## Answer Format Guidelines
### Language Style
**Write in conversational, practical language:**
- ❌ Avoid: "Consider the theoretical framework wherein..."
- ✅ Use: "Here's how it works in practice..."
- ❌ Avoid: "A sequence of tuples undergoes transformation..."
- ✅ Use: "Think of it like a conveyor belt where each item..."
- ❌ Avoid: academic jargon and formal definitions
- ✅ Use: everyday language and analogies
- ❌ Avoid: abstract explanations
- ✅ Use: concrete, real-world examples
**Make it practical:**
- Use real-world scenarios (fraud detection, IoT monitoring, trading systems)
- Explain through analogies and concrete situations
- Show trade-offs through actual use cases
- Connect concepts to problems you'd solve in industry
- Keep it engaging and easy to follow
### Direct Expert Discussion
Write as an expert would when explaining to a colleague or non-expert:
- Start directly with the answer or concept - no preambles
- Use conversational, non-academic language
- Explain complex ideas through real-world examples and practical scenarios
- Break down technical concepts into simple terms
- Focus on practical application over academic precision
- Use clear, engaging language that connects theory to practice
### Handling Incomplete or "Stupid" Questions
When questions seem incomplete or lack context:
- Ask clarifying questions back to get more information
- Acknowledge what you don't know and need to clarify
- Frame your response to guide toward a more complete understanding
- Remember: **Clever questions are sometimes more important than clever answers**
Example:
❌ "I cannot answer this question because it is incomplete..."
✅ "To give you a precise answer, I need to clarify: are you asking about X in the context of Y, or is it specifically about Z?"
### Discussing Approaches and Technologies
When explaining approaches taught in the course or discussing research papers:
- Explain the **why** behind the approach using real-world examples
- Compare different approaches using practical scenarios
- Use concrete examples from industry or real applications
- Discuss trade-offs through actual use cases
- Connect concepts to practical problems and solutions
- Avoid academic jargon; use everyday language
- Show how it works in practice, not just in theory
### Engagement Style
- **Interactive**: Frame responses as part of a discussion, not a lecture
- **Questioning**: Ask follow-up questions to deepen understanding
- **Analytical**: Examine assumptions, limitations, and alternatives
- **Comprehensive**: Cover key aspects while remaining focused
## Answer Structure
When structuring answers, follow this two-part approach:
### Part 1: Definition and Explanation (from course resources)
- Start with the definition and topic explanation from the lectures/materials
- Rewrite it in easy, non-academic language
- Explain what it is and how it works in simple terms
- Break down the concept without jargon
### Part 2: Real-World Examples
- Follow the definition with concrete, practical examples
- Use real-world scenarios to illustrate the concept
- Connect the theory to actual applications
- Make it relatable and understandable
**Structure:**
1. **Definition**: What it is (in easy language from the course materials)
2. **Explanation**: How it works (simplified from the resources)
3. **Example**: Real-world scenario that illustrates it
4. **Analysis** (if relevant): Trade-offs or alternative perspectives
### Visual Organization with Headers
**Use proper header hierarchy for better visual perspective and readability:**
- **Main questions** should use `##` (level 2 headers)
- **Major subsections** within answers should use `###` (level 3 headers)
- Examples: "Step-by-Step Process", "Real-World Example", "What Each Building Block Actually Is"
- **Sub-subsections** should use `####` (level 4 headers) when needed
- Examples: "Generalization/Specialization", "Temporal Context", "Event Channel Systems"
- Convert bold section labels to proper headers for better navigation
- Create clear visual hierarchy that makes answers easy to scan and navigate
**Benefits:**
- Makes long answers easier to navigate
- Improves readability and scannability
- Helps readers quickly find specific information
- Creates professional, well-organized documentation
- Enhances visual structure without changing content
### Answer Separation with Horizontal Rules
**Add horizontal rules (`---`) after every answer section to clearly indicate where each answer ends:**
- Place `---` after the last line of each complete answer
- This creates clear visual separation between different questions/answers
- Makes it easier to scan and identify where one answer ends and another begins
- Improves document navigation, especially in files with multiple answers
**Example:**
```markdown
## Question 1: What is X?
[Answer content here...]
---
## Question 2: How does Y work?
[Answer content here...]
---
```
**Benefits:**
- Clear visual indication of answer boundaries
- Easier to navigate between multiple answers
- Better document structure and organization
- Professional appearance with clear sections
Avoid:
- Over-introduction ("This is a great question...")
- Apologetic tones ("I'm sorry, but...")
- Skipping the definition and jumping straight to examples
- Using academic jargon from the source materials without simplification
- Dismissing or belittling questions
- Using only bold text for major sections instead of proper headers
- Flat structure without clear hierarchy
## Examples
### Scenario 1: Incomplete Question
**Question:** "What about query optimization?"
**❌ Weak Response:**
> "Your question is too vague. I cannot answer this without more specific information."
**✅ Strong Response:**
> "Query optimization covers several areas. Are you asking about:
> - Indexing strategies for stream processing?
> - Cost-based optimization in CQL?
> - Pattern matching efficiency in CEP?
>
> Each has different considerations depending on your use case."
### Scenario 2: Technical Concept with Definition + Example
**Question:** "Explain how ripple joins work."
**❌ Weak Response:**
> "Ripple joins are a type of join used in stream processing. They work by rippling through data. This is important for performance."
**✅ Strong Response:**
> **Definition:**
> Ripple joins are a way to join two data streams efficiently without keeping all the data in memory forever. Instead of buffering every piece of data until you find a match, ripple joins only look ahead a small window - like the ripple spreading out from a pebble in water. This limits how much memory you need while still finding matching records.
>
> The join works by maintaining a small lookahead window that moves forward through both streams. When tuples from different streams might match (based on timestamps and join conditions), they're kept in memory. Once a tuple is outside the window and can't match anything new, it's discarded.
>
> **Real-World Example:**
> Think of this like processing payments in a checkout system. Normally, you'd buffer everything and match later - like collecting all transactions and finding matches after hours. That uses tons of memory.
>
> With ripple joins, you only look ahead about 10 seconds. If two transactions from different payment systems match within that window, great - you process them. If not, you move on. This keeps memory low while still catching most real matches.
>
> The trick is setting the window size right - too small and you miss matches, too large and you're back to the memory problem. In practice, you base it on how delayed your data streams can be - like knowing your payment network has a max 5-second delay, so a 10-second ripple catches everything."
### Scenario 3: Discussion with Practical Context
**Question:** "How does the SASE model compare to traditional CEP systems?"
**❌ Weak Response:**
> "SASE is better than traditional CEP because it's newer and more flexible. It handles more types of queries."
**✅ Strong Response:**
> "Picture this: you're building a fraud detection system. Traditional CEP is like a hammer - if you only have hammers, you treat everything like a nail. Your engine uses time windows, so you have to force all queries into that window model, even when they'd work better as sequences.
>
> SASE gives you the whole toolbox. You can use window operators for the 'detect 5 transactions in 2 minutes' query, but also sequence operators for 'find this pattern of events in order.' You pick the tool based on what you're actually doing.
>
> Downside? Your runtime has to handle all those operator types efficiently. Imagine a Swiss Army knife - useful, but not as fast as a dedicated knife. If 90% of your queries follow one pattern (like our fraud system does), a specialized engine might be faster. But if you need variety (like a general monitoring system), SASE's flexibility is worth it."
## Remember
- **ALWAYS scan all available materials** (slides, notes, references) before generating any answer
- **Prioritize MD files** over PDFs when both exist, but read all formats if needed
- **Do a deep scan** of the repository to ensure comprehensive coverage
- Always follow the two-part structure: **Definition first** (in easy language from resources), **then examples**
- Write in conversational, non-academic language
- Use real-world examples and practical scenarios to explain concepts
- Break down complex ideas into simple terms
- Focus on practical application over theoretical precision
- Start with the definition from course materials but rewrite it simply
- Then follow with concrete examples that illustrate the concept
- You are the expert - demonstrate mastery through clear explanations
- Questions are starting points for discussion, not tasks to complete
- A good explanation uses everyday language and connects to real problems
- Engage with assumptions, limitations, and alternatives through concrete examples
- **Academic authenticity requires thorough material review** - never skip this step

View File

@ -1,178 +0,0 @@
---
id: rule-academic-lecture-reference-linking
alwaysApply: true
description: Guidelines for including course materials lists and inline references when writing exam answers or documentation that references course materials
author: Himel Das
---
# Lecture Reference Linking Rule
## Core Principle
When writing exam answers or documentation that references course materials, **always include both a course materials list at the top and inline references throughout the content**. This makes it clear which lectures support each part of your answer and helps readers verify sources.
## Course Materials List
**Always include a "Course Materials:" section at the top** of each answer file, listing all lectures used:
```markdown
Course Materials:
- [lecture-01](../lectures/lecture-01)
- [lecture-04](../lectures/lecture-04)
- [lecture-05](../lectures/lecture-05)
```
**Guidelines:**
- List **all lectures** that contain material used in the answers
- Use relative paths: `[lecture-XX](../lectures/lecture-XX)`
- Order lectures by number (lecture-01, lecture-02, etc.)
- Include the full list even if you only reference one lecture in a specific section
## Inline References
**Add inline references throughout your answers** wherever you draw from course materials:
**Format:**
- Use abbreviated format: `[L1](../lectures/lecture-01)`, `[L4](../lectures/lecture-04)`, etc.
- Place references at natural break points: after definitions, examples, or key concepts
- Multiple references can be combined: `([L1](../lectures/lecture-01), [L4](../lectures/lecture-04))`
**When to add references:**
✅ **Always reference when:**
- Stating a definition from a lecture
- Using examples directly from course materials
- Explaining concepts introduced in specific lectures
- Quoting or paraphrasing course content
- Referencing specific patterns, queries, or techniques taught
✅ **Reference placement examples:**
- After definitions: "**Concept X** is defined as... ([L4](../lectures/lecture-04))"
- After examples: "The system example ([L4](../lectures/lecture-04), [L5](../lectures/lecture-05)) demonstrates..."
- After code/queries: "```sql SELECT ... ``` ([L6](../lectures/lecture-06))"
- After key concepts: "The key advantage is **principle Y** ([L4](../lectures/lecture-04))"
❌ **Don't reference:**
- Generic knowledge that's common across multiple sources
- Your own explanations or analogies (unless they're directly based on a lecture)
- General examples you create yourself
## Reference Style Guidelines
### Abbreviated Format
Use **short abbreviations** for inline references to keep text readable:
- `[L1](../lectures/lecture-01)` instead of `[lecture-01](../lectures/lecture-01)`
- `[L4](../lectures/lecture-04)` instead of `[lecture-04](../lectures/lecture-04)`
### Placement
Place references **naturally in the flow**:
- At the end of sentences introducing concepts
- After definitions or key terms
- After examples or code blocks
- Before or after quoted material
**Good placement:**
```
**Concept X** is defined as a method that performs operations on data ([L4](../lectures/lecture-04)).
It works by processing information in a structured way...
```
**Avoid:**
- Breaking up sentences awkwardly just to add a reference
- Putting references in the middle of definitions
- Over-referencing the same concept multiple times in one paragraph
### Multiple References
When referencing multiple lectures:
- Combine them: `([L1](../lectures/lecture-01), [L4](../lectures/lecture-04))`
- Use when concepts span multiple lectures
- Place at the most relevant point in the text
## Examples
### ✅ Correct Structure
```markdown
# Topic Title
Course Materials:
- [lecture-01](../lectures/lecture-01)
- [lecture-04](../lectures/lecture-04)
- [lecture-05](../lectures/lecture-05)
## What is Concept X?
**Concept X** is defined as a method that performs operations on data ([L4](../lectures/lecture-04)).
It works by processing information in a structured way.
Think about the progression from **data** → **information** → **processed data** → **result** ([L1](../lectures/lecture-01), [L4](../lectures/lecture-04)):
- **Data** is raw representation...
```
### ✅ Reference After Examples
```markdown
**Pattern:** Detect when a specific condition occurs within a time window ([L6](../lectures/lecture-06)):
```sql
PATTERN SEQ(EventA+ a[], EventB b)
WHERE condition
WITHIN time_window
```
```
### ✅ Reference for Specific Concepts
```markdown
The key advantage is **decoupling** ([L4](../lectures/lecture-04)) - components don't need to know what other components will do with the data.
```
### ❌ Missing Course Materials List
```markdown
# Topic Title
## What is Concept X?
**Concept X** is defined as a method...
```
### ❌ No Inline References
```markdown
Course Materials:
- [lecture-04](../lectures/lecture-04)
## What is Concept X?
**Concept X** is defined as a method that performs operations on data.
It works by processing information...
```
## Checklist
When writing exam answers with lecture references:
✅ Course Materials section at the top with all used lectures
✅ Inline references after definitions from lectures
✅ Inline references after examples from course materials
✅ Inline references for specific patterns, queries, or techniques
✅ Abbreviated format ([L1], [L4]) for readability
✅ Natural placement that doesn't disrupt flow
✅ Multiple references combined when appropriate
## Remember
- **Always include both**: Course materials list at top AND inline references throughout
- **Be consistent**: Use the same abbreviated format ([L1], [L4]) throughout
- **Reference appropriately**: Don't over-reference, but don't miss important citations
- **Keep it readable**: References should enhance clarity, not clutter the text
- **Link to actual lectures**: Make sure paths are correct and lectures exist
- **Complete coverage**: If you use material from a lecture, include it in both the list and inline references

View File

@ -1,161 +0,0 @@
---
id: rule-academic-mermaid-diagrams
alwaysApply: false
description: Guidelines for adding Mermaid diagrams to exam answers and documentation with automatic SVG generation support
author: Himel Das
---
# Mermaid Diagrams in Documentation
## Core Principle
When answering questions or creating documentation that would benefit from visual diagrams, **always include corresponding Mermaid diagrams**. Diagrams should be in separate files in a `diagrams/` directory at the same level as the documentation file.
## Directory Structure
```
documentation-directory/
├── README.md (or other documentation file)
└── diagrams/
├── diagram-name.mmd
└── diagram-name.svg (if auto-generation is configured)
```
**Rules:**
- Create `diagrams/` directory at the same level as the documentation file
- Use descriptive, kebab-case names for diagram files
- Place all related diagrams in the same `diagrams/` directory
## Auto-Generation Detection
Check if auto-generation is configured by looking for:
1. `.vscode/settings.json` with `emeraldwalk.runonsave` configuration
2. `scripts/mermaid/generate-svgs.py` script exists
**If auto-generation is configured:**
- Create `.mmd` files in `diagrams/` directory
- Reference `.svg` files in documentation: `![Description](diagrams/diagram-name.svg)`
- SVG files will be auto-generated when `.mmd` files are saved
**If auto-generation is NOT configured:**
- Embed Mermaid diagrams directly in markdown using ` ```mermaid ` code blocks
## When to Add Diagrams
Add diagrams for:
- System architectures or component relationships
- Data flows or process flows
- Concept relationships
- Sequences or workflows
- Hierarchical structures
- State transitions
## Diagram Quality
- Clear and easy to understand
- Directly relevant to the content
- Include all relevant components
- Use descriptive labels
- Maintain consistent styling
## Subgraph Layout Guidelines
### Subgraph Orientation Preference
**Whenever possible, arrange subgraphs horizontally (side-by-side) rather than vertically.** This provides better use of horizontal space and is generally more readable for comparison diagrams.
### Stacking Unconnected Subgraphs Vertically
When you need to stack two or more unconnected subgraphs vertically (one below the other), use the following technique:
**Problem:** Mermaid may render unconnected subgraphs side-by-side even when using `graph TB` (top-bottom direction).
**Solution:** Add an invisible connection between subgraphs using the invisible edge syntax (`~~~`):
```mermaid
graph TB
subgraph "First Subgraph"
direction LR
A[Node A] --> B[Node B]
end
subgraph "Second Subgraph"
direction LR
C[Node C] --> D[Node D]
end
First Subgraph ~~~ Second Subgraph
```
**Key Points:**
- Use `graph TB` for the main graph direction (top-bottom)
- Set `direction LR` within each subgraph to keep internal nodes horizontal
- Add invisible connection: `SubgraphName1 ~~~ SubgraphName2` (use subgraph IDs or labels)
- The invisible edge (`~~~`) doesn't render visually but forces vertical stacking
- This ensures the first subgraph appears on top and the second below it
### Forcing Horizontal Layout Within Subgraphs
When nodes within a subgraph need to be arranged horizontally but Mermaid is rendering them vertically:
**Solution:** Connect the nodes sequentially with simple lines (`---`) or arrows (`-->`) to force horizontal arrangement:
```mermaid
subgraph "Event Sequence"
direction LR
EVENT1[Event 1] --- EVENT2[Event 2]
EVENT2 --- EVENT3[Event 3]
EVENT3 --- EVENT4[Event 4]
EVENT1 -.->|Action 1| PROCESSOR
EVENT2 -.->|Action 2| PROCESSOR
EVENT3 -.->|Action 3| OUTPUT
EVENT4 -.->|Action 4| OUTPUT
end
```
**Key Points:**
- Use `direction LR` within the subgraph
- Connect nodes horizontally first (EVENT1 → EVENT2 → EVENT3 → EVENT4)
- Then add connections to external nodes using dotted lines (`-.->`) to reduce visual clutter
- The horizontal connections force the nodes to arrange left-to-right
### Fixing Subgraph Titles That Appear Behind Graphs
When subgraph titles are obscured or appear behind graph elements:
**Problem:** Subgraph labels may be rendered behind nodes or edges, making them difficult to read.
**Solution:** Add explicit title nodes at the top of each subgraph with dotted connections to the first nodes:
```mermaid
graph TB
subgraph "Section Title"
TITLE["Section Title"]
FIRST[First Node]
SECOND[Second Node]
TITLE -.-> FIRST
FIRST --> SECOND
end
```
**Key Points:**
- Create a title node with the same text as the subgraph label (use quotes if the text contains special characters like parentheses)
- Connect the title node to the first content node using a dotted line (`-.->`)
- Style the title node differently (e.g., different background color) to distinguish it from content nodes
- This ensures the title is visible and properly positioned at the top of the subgraph
## Examples
**Auto-generation configured:**
```markdown
![Diagram Description](diagrams/diagram-name.svg)
```
**Auto-generation NOT configured:**
```markdown
```mermaid
graph TB
A[Component A] --> B[Component B]
```
```

View File

@ -1,153 +0,0 @@
---
id: rule-academic-short-answer-version
alwaysApply: false
description: Guidelines for creating short/concise versions of detailed answers
author: Himel Das
---
# Short Answer Version Rule
## Core Principle
When creating short versions of detailed answers, create a **super concise version** that is short and easy to study quickly, while remaining **fully understandable** when read independently. This version provides a condensed format for quick review and study.
## File Naming
**Format:** Add `-short` suffix to the detailed version filename
- If detailed version is `README.md` → short version is `README-short.md`
- If detailed version is `detailed-answers.md` → short version is `detailed-answers-short.md`
- Place in the same directory as the detailed version
- Use the same directory structure as detailed answers
- Keep the same file organization
## Content Requirements
### Length and Conciseness
**Target:** Reduce content significantly (typically 50-70% reduction) while maintaining:
- **Complete understanding** - someone reading only this version should understand the full picture
- **Key concepts** - all essential definitions and explanations
- **Critical examples** - simplified but meaningful real-world examples
- **Important distinctions** - key differences and comparisons
### Structure
**Maintain the same structure as detailed version:**
- Same header structure and organization
- Same question headers (with any importance markers preserved)
- Same diagram references (use ALL diagrams from detailed version)
- Same section separators (horizontal rules, etc.)
**Navigation Links:**
- **CRITICAL:** Add a navigation link at the beginning of each answer section (right after the question header)
- **Format:** `[📖 View detailed answer](./detailed-filename.md#anchor-name)` where `detailed-filename.md` is the name of the detailed version file
- **Anchor format:** Convert header text to anchor by:
- Converting to lowercase
- Replacing spaces with hyphens
- Removing special characters (?, ✓, etc.)
- **IMPORTANT:** If special characters are removed from the end of the header, add a trailing hyphen to the anchor
- **Example:** If detailed version is `README.md` and header is "What is a concept? ✓✓", link becomes `[📖 View detailed answer](./README.md#what-is-a-concept-)` (note the trailing hyphen after removing ✓✓)
- **Purpose:** Allows easy navigation from short version to corresponding detailed section
**Content organization:**
- Use paragraphs when needed for clarity
- Use bullet points for lists and comparisons
- Use tables for side-by-side comparisons (simplified)
- Keep essential examples but make them more concise
### Diagram Usage
**CRITICAL:** Use **ALL the same figures/diagrams** from the detailed version:
- Reference the exact same diagram files
- Do NOT create any new figures for the concise version
- Maintain all diagram references in the same positions
- Diagrams help understanding even in concise format
### Formatting Guidelines
**Bold important points:**
- **Key terms and concepts** when first introduced
- **Critical distinctions** and differences
- **Main characteristics** of systems, approaches, or methods
- **Core principles** and definitions
**Use emphasis strategically:**
- Bold for definitions and key concepts
- Italic for emphasis on specific aspects
- Keep formatting consistent with detailed version style
### Content Selection
**What to include:**
- ✅ Core definitions and explanations
- ✅ Key characteristics and features
- ✅ Essential differences and comparisons
- ✅ Simplified but meaningful examples
- ✅ Critical concepts and principles
- ✅ Important trade-offs and considerations
**What to condense or remove:**
- ❌ Extended explanations and elaborations
- ❌ Multiple similar examples (keep one best example)
- ❌ Detailed step-by-step processes (summarize)
- ❌ Extensive background information
- ❌ Repetitive explanations
- ❌ Overly detailed sub-sections
### Writing Style
**Maintain academic standards:**
- Follow all applicable academic formatting rules
- Include source materials list if required by academic standards
- Include inline references to sources if required
- Use neutral language (no "you")
- Maintain conversational but professional tone
**Conciseness techniques:**
- Combine related points into single sentences
- Use parallel structure for comparisons
- Eliminate redundant phrases
- Focus on essential information
- Use clear, direct language
### Example Transformation
**Detailed version:**
```
A concept is a fundamental idea or principle in a domain. In computing, it's also the abstract representation that models real-world phenomena. Concepts are structured knowledge - specifically, they're what you get when you take raw information and add meaning plus relationships about how elements connect and interact.
Think of the progression from data → information → concept like this: raw data is just numbers or symbols. Add semantics and it becomes information. Add relationships and structure, and it becomes a concept.
```
**Concise version:**
```
A **concept** is a fundamental idea in a domain - it's **structured knowledge** (semantics + relationships).
**Progression:** **Data** → **Information** → **Concept**
```
## Quality Checklist
When creating concise versions, ensure:
✅ Content reduced by 50-70% while maintaining understanding
✅ All key concepts and definitions included
✅ All diagrams from detailed version referenced
✅ Important points are bolded
✅ Source materials and inline references included (if required)
✅ Section separators maintained
✅ Question headers with any markers preserved
✅ Navigation links added at beginning of each answer section (link to detailed version filename)
✅ Can be understood independently without detailed version
✅ Suitable for quick study and preparation
✅ Follows all applicable formatting rules
## Remember
- **Concise but complete** - short enough for quick study, complete enough for understanding
- **Same diagrams** - use all figures from detailed version, no new ones
- **Bold key points** - make important concepts stand out
- **Maintain structure** - keep same organization as detailed version
- **Navigation links** - add link to detailed version at start of each answer
- **Short format** - optimized for quick review and study

View File

@ -1,74 +0,0 @@
---
id: rule-design-svg-icon-centering
alwaysApply: true
description: Guidelines for creating and editing SVG icons with properly centered content using mathematical calculations
author: Himel Das
---
# SVG Icon Centering
When creating or editing SVG icons, ensure the content is centered both vertically and horizontally within the viewBox.
## Centering Principle
Content should be positioned so its geometric center aligns with the viewBox center.
## Calculation Technique
### Step 1: Identify ViewBox Center
For `viewBox="0 0 width height"`:
- **Horizontal center**: `width / 2`
- **Vertical center**: `height / 2`
Example: `viewBox="0 0 2048 2048"` → center is `(1024, 1024)`
### Step 2: Calculate Content Bounds
Find the minimum and maximum coordinates of the content in local coordinates (before transforms):
- `min_x`, `max_x` for horizontal bounds
- `min_y`, `max_y` for vertical bounds
### Step 3: Calculate Content Center
- **Content horizontal center**: `(min_x + max_x) / 2`
- **Content vertical center**: `(min_y + max_y) / 2`
### Step 4: Calculate Required Translation
When using `transform="translate(tx, ty) scale(s)"`:
To center the content:
- `tx = viewBox_center_x - (content_center_x × scale)`
- `ty = viewBox_center_y - (content_center_y × scale)`
Rearranging for translation needed:
- `tx = viewBox_center_x - (content_center_x × s)`
- `ty = viewBox_center_y - (content_center_y × s)`
### Example Calculation
Given:
- ViewBox: `0 0 2048 2048` (center at 1024, 1024)
- Content bounds: y from -35 to 25 (local coordinates)
- Scale: 22
Calculate:
1. Content vertical center: `(-35 + 25) / 2 = -5`
2. Required ty: `1024 - (-5 × 22) = 1024 + 110 = 1134`
3. Result: `transform="translate(1024, 1134) scale(22)"`
## Verification
After positioning, verify centering:
1. Calculate where content center maps to: `translate_value + (content_center × scale)`
2. Compare with viewBox center
3. Adjust if difference is significant
## Rules
- Always calculate mathematically rather than visually adjusting
- Account for scale factors in transformations
- Consider stroke width in bounds calculations for outline elements
- Verify both horizontal and vertical centering independently
- Document calculations in SVG comments when non-obvious

View File

@ -1,158 +0,0 @@
---
id: rule-documentation-documentation-formatting
alwaysApply: true
description: Guidelines for formatting markdown documentation to improve readability and scannability
author: Himel Das
---
# Documentation Formatting Rule
## Core Principle
When writing documentation in markdown files, use formatting (bold, italic, lists, etc.) to make content easy to scan and read. Good formatting helps readers quickly identify key concepts, examples, and important information.
## Formatting Guidelines
### Key Terms and Concepts
**Always bold key terms** when first introduced or when they're central to the explanation:
- Core concepts and important terms
- Technical terms that are being defined or explained
- Important phrases and definitions
### Progressions and Sequences
Use arrow notation for showing progression or relationships:
- **Step 1** → **Step 2** → **Step 3**
- **Definition** → **Explanation** → **Example**
- **Input** → **Process** → **Output**
### Examples and Code
- Precede examples with **Example:** in bold when the example is separate from the main flow
- Use backticks for code snippets, filenames, and technical terms: `` `config.json` ``, `` `variable_name` ``
- Use inline code for technical terms in contexts where they're code entities or data structures
### Power Notation
**Always use superscript format** for all power notations instead of caret notation:
- ✅ Use: `10⁴`, `10⁵`, `N²`, `N³`, `2ⁿ`
- ❌ Avoid: `10^4`, `10^5`, `N^2`, `N^3`, `2^N`
This applies to:
- Numeric powers: `10⁴`, `2³¹`, `10⁸`
- Variable powers in Big O notation: `O(N²)`, `O(N³)`, `O(2ⁿ)`
- Mathematical expressions: `N²log(N)`, `2ⁿ + N²`
- All contexts where powers appear in documentation
### Lists
Convert series of related examples or points into bulleted lists:
- Makes multiple examples easier to scan
- Bold the key term at the start of each bullet when listing different types or examples
- Keep list items parallel in structure
### Tables
**Always format tables with proper column alignment** for better readability:
- Align column separators (`|`) vertically
- Use consistent spacing within columns
- Pad shorter entries with spaces to match column width
- Bold important entries when needed
- Use emoji indicators (✅, ❌, ⚠️) for status columns when helpful
### Exercise Questions and Answer Options
When formatting multiple-choice questions or exercises with answer options, use checkbox symbols to indicate correct and incorrect answers:
**Format:**
- Use **`**Answer**`** as a section header (bold)
- List all options as bullet points with checkbox symbols:
- ✓ (checkmark) for correct answers
- □ (empty box) for incorrect/unselected answers
- Each option should be on its own line with the checkbox symbol at the start
**Example:**
```
**Answer**
- □ Option A
- ✓ Option B
- □ Option C
- □ Option D
**Explanation**: Brief explanation of why Option B is correct.
```
**Guidelines:**
- Always include all answer options, not just the correct one
- Use consistent checkbox symbols throughout the document
- Place the **Answer** section immediately after the question
- If an explanation is provided, directly incorporate it as-is after the **Answer** section
- Use **`**Explanation**`** as a section header (bold) when including explanations
### Emphasis
Use *italic* for:
- Emphasis on specific actions or temporal aspects: "*as they occur*", "*in real-time*"
- Drawing attention to how something works differently than expected
- Soft emphasis that doesn't require bold
Use **bold** for:
- Key terms and concepts
- Section labels (like "Example:", "Definition:", "Note:")
- Important phrases or definitions
### Structure
- Use clear hierarchy: `#` for main sections, `##` for subsections, `###` for sub-subsections
- Separate examples from explanations with blank lines
- Use lists when you have 3+ related items instead of cramming them into a paragraph
## Formatting Checklist
When formatting documentation, ensure:
✅ Key terms are bolded
✅ Progressions use arrow notation
✅ Examples are clearly labeled with bold "Example:" if separate
✅ Multiple related examples are in a bulleted list
✅ Code snippets and technical terms use backticks
✅ Important distinctions are emphasized with bold or italic
✅ Power notations use superscript format (10⁴, N², 2ⁿ) instead of caret notation
✅ Tables are properly aligned with consistent column spacing
✅ Exercise answer options use checkbox symbols (✓ for correct, □ for incorrect)
✅ The text is easy to scan visually
## Examples
### ❌ Poorly Formatted
```
The application uses a three-stage processing pipeline. First, raw data is collected from various sources. This data goes through validation where invalid entries are filtered out. Finally, the validated data is transformed and stored in the database.
The system supports several data formats. JSON format is used for API responses. CSV format is used for bulk data imports. XML format is still supported for legacy systems. YAML format is used for configuration files.
For example, when a user submits a form, the data is first validated. If validation passes, it gets processed and stored. The user receives a confirmation message. If validation fails, an error is shown.
```
### ✅ Well Formatted
```
The application uses a three-stage processing pipeline: **Raw Data Collection** → **Validation** → **Transformation & Storage**. First, raw data is collected from various sources. This data goes through validation where invalid entries are filtered out. Finally, the validated data is transformed and stored in the database.
The system supports several data formats:
- **JSON** format is used for API responses
- **CSV** format is used for bulk data imports
- **XML** format is still supported for legacy systems
- **YAML** format is used for configuration files
**Example:** When a user submits a form, the data is first validated. If validation passes, it gets processed and stored. The user receives a confirmation message. If validation fails, an error is shown.
```
## Remember
- Formatting should enhance readability, not distract from content
- Be consistent with formatting choices throughout the document
- When in doubt, bold key terms and use lists for multiple examples
- The goal is to make documentation scannable while maintaining clarity and readability

View File

@ -1,88 +0,0 @@
---
id: rule-documentation-documentation
alwaysApply: true
description: Rules for documentation structure, file naming conventions, source attribution, code comments style, and linking patterns. Ensures consistent markdown organization and neutral, professional documentation.
author: Himel Das
---
# Documentation
## File Structure
- When creating multiple md files for a feature, create a dedicated directory in `docs/`
- Each feature directory MUST have a `README.md` file
## Source Links
- ✅ If a source URL or link is provided during documentation creation, include it below the header
- ✅ Format: `[Source](URL)` placed directly after the main title
- ✅ Use markdown link format for consistency
- ❌ Don't include source links if no URL is provided
- ❌ Don't place source links in other locations (e.g., footer, separate section)
### Examples
- ✅ Good:
```markdown
# Document Title
[Source](https://example.com/resource)
## Section 1
```
- ❌ Bad: Placing source link at the end or in a separate section
- ❌ Bad: Including source link when no URL is provided
## File Naming
- Use lowercase words separated by dashes
- Format: `file-name.md`
## Examples
```
docs/
feature-name/
README.md
setup-guide.md
troubleshooting.md
```
## Rules
- ✅ Group related docs in feature directories
- ✅ Always include README.md in feature directories
- ✅ Use kebab-case for all md filenames
- ❌ Don't use spaces or underscores in filenames
- ❌ Don't use uppercase letters in filenames
## Comments in Code
- ✅ Use neutral, descriptive language
- ✅ Focus on WHAT and WHY, not ownership
- ❌ Don't use possessive pronouns like "your", "your project", "yours"
- ❌ Don't use template-style placeholder language
### Examples
- ✅ Good: `// 1200x630 image in public folder`
- ❌ Bad: `// Your 1200x630 image in public folder`
## File Linking in Documentation
- ✅ Always use markdown links when referencing files
- ✅ Use relative paths from the current file location
- ✅ Format: `[File Name](./relative/path/to/file.ext)]`
- ✅ Make links descriptive and clickable
- ❌ Don't use plain text file references without links
- ❌ Don't use absolute paths in markdown files
### Examples
- ✅ Good: `See [schema.json](./schema.json) for full type definitions`
- ✅ Good: `Example in [alphabets.json](./a1/alphabets.json)`
- ❌ Bad: `See schema.json` or `See "schema.json"`
- ❌ Bad: `See /Users/admin/project/file.json`
## Code in Documentation
- ✅ Link to actual implemented files instead of duplicating code
- ✅ Use file references when code already exists in the codebase
- ✅ Remove large code blocks and replace with links
- ✅ Keep only concise snippets or pseudocode for explanation
- ❌ Don't duplicate entire implementations from files
- ❌ Don't copy large code blocks that are already in the codebase
### Examples
- ✅ Good: `See: [quiz-session.ts](./quiz-session.ts)`
- ✅ Good: `Link to: [types.ts](/src/components/quiz/types.ts)`
- ❌ Bad: Copying 200 lines of code that already exist in a file

View File

@ -1,112 +0,0 @@
---
id: rule-documentation-human-writing-style
alwaysApply: true
description: Rules for writing naturally and authentically - avoid robotic AI tone in documentation, code comments, error messages, and explanations. Write like a human colleague, not a customer service bot.
author: Himel Das
---
# Human Writing Style Rule
## Core Principle
When generating content or documentation, write it like a human would - naturally, casually, and authentically. Avoid the robotic, overly polished tone that AI often defaults to.
## What to Avoid (AI Voice Cues)
❌ **Never use phrases like:**
- "I'm here to help you..."
- "Certainly! I can assist you with..."
- "Let me break that down for you..."
- "I understand you want to..."
- "Here's what I'd recommend..."
- "I've analyzed the situation and..."
- "Please let me know if you have any questions..."
- "I hope this helps!"
- "Does this answer your question?"
- "I'd be happy to help with..."
- Overuse of bullet points for everything
- Opening every paragraph with a transition phrase
- Over-apologetic tone ("I'm sorry, but...", "Unfortunately...")
- Signing off explicitly ("Best regards", "Sincerely")
- Using emojis excessively or in professional contexts
- Being overly enthusiastic with punctuation (multiple !!!, ???)
- Using corporate jargon unnecessarily
- Repeating the user's words back to them
## What to Do Instead
✅ **Write naturally:**
- Start explanations directly without preamble
- Use varied sentence structure (mix of short and long sentences)
- Write in active voice
- Be direct and concise
- Show personality when appropriate (for docs, not formal reports)
- Use contractions in informal contexts
- Don't over-structure with headers/bullets unless needed
- End naturally without trying to wrap up every section
## Voice & Tone Guidelines
### Documentation
- **Tone:** Clear, helpful, and professional without being stiff
- **Voice:** Like explaining to a colleague, not a helpdesk
- **Length:** Say what needs to be said, not more
- Example:
- ❌ "Welcome! In this section, I'll be guiding you through..."
- ✅ "This section covers the basics of X. Here's what you need to know..."
### Code Comments
- Write like you're talking to your future self
- Explain *why*, not *what* the code does
- Be conversational, not robotic
### Error Messages
- Be helpful but not condescending
- Don't over-apologize
- Example:
- ❌ "I'm sorry, but it looks like an error occurred. Please try again!"
- ✅ "Connection failed. Check your network settings."
### Explanations
- Start with the answer, not a setup
- Don't repeat the question back
- Use analogies naturally when they help
- Example:
- ❌ "You've asked about how X works. That's a great question! Here's what you need to know..."
- ✅ "X works like [analogy]. In practice, this means..."
## Quick Tests for Human-Like Writing
1. **Could a colleague have written this?** If no, rewrite.
2. **Am I reading the same transition phrases over and over?** If yes, vary the structure.
3. **Does it sound like it's trying too hard to be helpful?** If yes, tone it down.
4. **Would I say this out loud to someone?** If no, simplify.
5. **Did I just explain what I'm about to do instead of doing it?** If yes, delete the setup and start.
## Examples
### ❌ Too AI-like
> "I'd be happy to help you understand the concept of X! Let me break this down for you. X is essentially a way to accomplish Y. Here are some key points to remember..."
### ✅ More Human
> "X does Y by... [direct explanation]. Keep in mind that... [why it matters]."
### ❌ Too AI-like
> "Certainly! I can assist you with that issue. Let me provide you with a comprehensive breakdown of the steps involved..."
### ✅ More Human
> "Here's how to fix it: [steps]. The key thing is... [important detail]."
## Red Flags (Auto-Detect These)
If you see these patterns, rewrite:
- Opening multiple paragraphs with "In order to..." or "To understand..."
- Using the same transition repeatedly ("Additionally", "Furthermore", "Moreover")
- Explaining what you'll explain instead of explaining it
- Over-structuring with unnecessary headers for simple points
- Apologizing when there's nothing to apologize for
- Using corporate buzzwords when plain language works better
## Remember
The goal is to write documentation that feels like a knowledgeable person wrote it, not a customer service bot. Be helpful, but be real.

View File

@ -1,29 +0,0 @@
---
id: rule-documentation-line-wrapping
alwaysApply: false
description: Guidelines for wrapping text lines at approximately 120 characters for better readability in documentation
author: Himel Das
---
# Line Wrapping Rule
## Core Principle
All text (paragraphs, list items, and summary points) should be wrapped at word boundaries to maximize line length, staying as close to 120 characters as possible. Avoid unnecessary breaks—only break when approaching the 120-character limit.
## Formatting Guidelines
### Paragraph Formatting
Paragraphs should be wrapped at word boundaries, with each line as close to 120 characters as possible. Separate paragraphs with blank lines. Do not create unnecessarily short lines—maximize usage of the 120-character limit.
### List Item Formatting
List items and summary points should also be wrapped at word boundaries, maximizing line length close to 120 characters.
## Example
For a long sentence like "The implementation of this feature requires careful consideration of multiple factors including performance optimization, security best practices, and user experience design", wrap at word boundaries to maximize usage:
- Line 1: "The implementation of this feature requires careful consideration of multiple factors including performance optimization, security" (close to 120 chars)
- Line 2: "best practices, and user experience design." (continuation)

View File

@ -1,103 +0,0 @@
---
id: rule-documentation-sequential-documentation
alwaysApply: true
description: Rules for organizing feature documentation sequentially when implementing new features. Determines whether to use sequential numbering and folder structure based on existing documentation patterns.
author: Himel Das
---
# Sequential Documentation
When implementing a new feature and creating documentation for it, follow these rules to determine where to place the documentation and whether to use sequential numbering.
## Decision Tree
### 1. Check for `docs/steps/` Directory
**If `docs/steps/` exists:**
- Proceed to check for sequential numbering pattern
**If `docs/steps/` does NOT exist:**
- Place documentation directly in `docs/` directory
- Do NOT use sequential numbering
### 2. Check for Sequential Numbering Pattern
**If `docs/steps/` exists AND contains files with sequential numbers (e.g., `1-feature.md`, `2-feature.md`):**
- Add new documentation with the next sequential number
- Format: `N-feature-name.md` where N is the next number in sequence
- Place in `docs/steps/` directory
**If `docs/steps/` exists BUT does NOT contain sequentially numbered files:**
- Add documentation in `docs/steps/` directory
- Do NOT add sequential numbering
- Use standard kebab-case naming: `feature-name.md`
## Examples
### Scenario 1: Sequential Documentation Exists
```
docs/
steps/
1-initialization.md
2-menu-bar-icon.md
3-command-execution.md
```
**Action:** Add new feature doc as `4-new-feature.md` in `docs/steps/`
### Scenario 2: Steps Folder Exists, No Sequential Pattern
```
docs/
steps/
setup-guide.md
troubleshooting.md
configuration.md
```
**Action:** Add new feature doc as `new-feature.md` in `docs/steps/`
### Scenario 3: No Steps Folder
```
docs/
README.md
setup.md
api-guide.md
```
**Action:** Add new feature doc as `new-feature.md` directly in `docs/`
## Rules
- ✅ Always check for `docs/steps/` directory first
- ✅ Look for existing sequential numbering pattern
- ✅ Match the existing documentation structure
- ✅ Use kebab-case for all documentation filenames
- ❌ Don't create sequential numbering if it doesn't already exist
- ❌ Don't mix sequential and non-sequential docs in the same directory
- ❌ Don't skip numbers in the sequence
## Sequential Numbering Format
When using sequential numbering:
- Format: `N-feature-name.md`
- N is an integer starting from 1
- Use single dash between number and name
- Use kebab-case for the feature name portion
- Examples: `1-setup.md`, `2-authentication.md`, `10-deployment.md`
## When to Create Sequential Documentation
Sequential documentation is useful for:
- Implementation steps that build on each other
- Feature development timeline
- Tutorial or guide progression
- Migration or upgrade steps
Sequential documentation may NOT be appropriate for:
- Reference documentation
- Independent feature docs
- API documentation
- General guides

View File

@ -1,88 +0,0 @@
---
id: rule-electron-project-organization
alwaysApply: true
description: Rules for organizing Electron projects with clear separation between foundational/template code and application-specific code. Template code goes in src/, app-specific code goes in src/app/.
author: Himel Das
---
# Electron Project Organization
## Core Principle
Separate foundational/template code from application-specific code:
- **Foundational/Template Code** → `src/` - Reusable across Electron projects
- **Application-Specific Code** → `src/app/` - Specific to this application
## Directory Structure
### Foundational Utilities (`src/utils/`)
Generic utilities reusable across projects:
- Platform-specific utilities (icon paths, file system helpers)
- Framework configuration (logging, protocol handlers)
- System integration (tray, window management, auto-updater)
- Generic helpers that work across different applications
These utilities have no dependencies on application-specific code and can be extracted for use in other projects.
### Application Utilities (`src/app/utils/`)
Application-specific utilities:
- Feature-specific storage and data management
- Application-specific file operations
- Business logic specific to the application domain
- Domain-specific helpers and validators
These utilities depend on application-specific types, data structures, or business logic.
### Foundational Components (`src/components/`)
Global library components and shared UI:
- Component library components
- Theme providers and utilities
- Generic UI components
- App wrapper components
These components are reusable and not tied to specific application features.
### Application Components (`src/app/components/`)
Application-specific components:
- Feature-specific layouts
- Domain-specific components
- Application-specific icons and assets
- Business logic components
These components implement application-specific functionality and UI.
## Rules
### ✅ DO
- Place reusable Electron utilities in `src/utils/`
- Place application-specific utilities in `src/app/utils/`
- Place library/shared components in `src/components/`
- Place application-specific components in `src/app/components/`
- Keep foundational code independent of application code
- Make foundational utilities importable by application code
### ❌ DON'T
- Mix foundational and application-specific code
- Place application-specific logic in foundational utilities
- Place reusable utilities in application directories
- Create dependencies from foundational code to application code
- Include application-specific types or data in foundational code
## Benefits
- **Reusability**: Foundational code can be extracted for other projects
- **Clear boundaries**: Easy to identify what's template vs application-specific
- **Maintainability**: Clear separation makes code easier to understand and modify
- **Template-friendly**: Foundation code serves as a reusable template
- **Scalability**: Easy to add new features without affecting foundational code

View File

@ -1,46 +0,0 @@
---
id: rule-general-articles-in-comments
alwaysApply: true
description: Enforce proper use of articles (a, an, the) in comments to maintain grammatical correctness and readability.
author: Himel Das
---
# Proper Use of Articles in Comments
All comments must include appropriate articles ('a', 'an', 'the') where necessary to maintain grammatical correctness and readability.
## Rules
1. Use "the" when referring to a specific or previously mentioned item
2. Use "a" or "an" when introducing a new, non-specific item
3. Use "an" before words starting with a vowel sound
4. Do not omit articles where they are grammatically required
## Examples
### Correct Usage
- ✅ "Initialize the database connection."
- ✅ "Create an instance of the User class."
- ✅ "Add a new item to the list."
- ✅ "Build the command based on the platform."
- ✅ "Handle the Finder separately (macOS only)."
- ✅ "Get the icon path for the window."
- ✅ "Open the project in the specified IDE."
### Incorrect Usage
- ❌ "Initialize database connection." → "Initialize **the** database connection."
- ❌ "Create instance of User class." → "Create **an** instance of **the** User class."
- ❌ "Add new item to list." → "Add **a** new item to **the** list."
- ❌ "Build command based on platform." → "Build **the** command based on **the** platform."
- ❌ "Handle Finder separately." → "Handle **the** Finder separately."
- ❌ "Get icon path for window." → "Get **the** icon path for **the** window."
- ❌ "Open project in specified IDE." → "Open **the** project in **the** specified IDE."
## Exceptions
- Code examples or technical terms that are conventionally written without articles
- Variable names or function names in comments
- URLs or file paths
- Short imperative commands where articles would be awkward (e.g., "Save file" in UI labels)

View File

@ -1,52 +0,0 @@
---
id: rule-general-code-migration
alwaysApply: true
description: Guidelines for ensuring all references are updated when moving files or directories. Covers code references, configuration files, documentation, and verification steps.
author: Himel Das
---
# Code Migration
When moving files or directories, ensure all references are updated.
## Move Files
- Move files or directories to the new location
- Verify the new structure
## Update Code References
- Search and update all imports, includes, and requires to the new path
- Check internal imports within moved files
- Verify no circular dependencies are introduced
## Configuration Files
- Update build tool configurations
- Update compiler and linter configurations
- Update path aliases and module resolution settings
- Update include and exclude patterns
## Documentation
- Update README files
- Update documentation files
- Update code examples
- Update file structure references
## Verification
- Search for old path references
- Search for new path references and verify they exist
- Ensure build or compilation succeeds
- Verify no errors or warnings
- Confirm the application functions correctly
## Success Criteria
- All references updated
- Configuration files verified
- Documentation updated
- No broken linkages
- Build succeeds
- Application works correctly

View File

@ -1,24 +0,0 @@
---
id: rule-general-comment-alignment
alwaysApply: false
description: Align inline comments within blocks using longest-line + 2 spaces
author: Himel Das
---
# Inline Comment Alignment
## Process
1. **Block** = consecutive lines with inline `#` comments
2. **Longest** = max length (code before `#`, stripped) in block
3. **Target** = longest + 2 spaces before `#`
4. **Pad** shorter lines so `#` aligns at target column
## Example
```python
def process():
result = [8]
result.insert(2, 0) # [2, 4, 0, 6, ...]
return result # [2, 4, 0, 6, ...]
```

View File

@ -1,75 +0,0 @@
---
id: rule-general-feature-organization
alwaysApply: true
description: Rules for organizing feature code in single directories. All feature-related code (types, hooks, components, utils) must be grouped together in one feature directory.
author: Himel Das
---
# Feature Organization
## Core Principle
When implementing a feature, ALL related code must be in ONE directory:
```
src/components/feature-name/
├── types.ts # All TypeScript interfaces for this feature
├── hooks/
│ ├── useFeature.ts # Custom hooks
│ └── useFeatureState.ts
├── components/
│ ├── FeatureComponent.tsx
│ └── FeatureWrapper.tsx
├── utils/
│ ├── featureHelpers.ts
│ └── featureConstants.ts
├── data/
│ └── featureData.json # If feature has its own data files
└── index.ts # Public API exports
src/pages/
└── feature-name/ # Feature-specific pages
├── index.mdx
└── settings.mdx
```
## Rules
### ✅ DO
- Keep all feature code in one directory
- Include types, hooks, components, utilities together
- Use `index.ts` for clean public exports
- Group by functionality within the feature directory
### ❌ DON'T
- Split feature code across multiple locations
- Mix feature components with general components
- Create separate directories for types/hooks/components of the same feature
## Example: Quiz Feature
```
src/components/quiz/ # ✅ All quiz code here
├── types.ts # Quiz interfaces
├── hooks/
│ └── useQuizSession.ts
├── components/
│ ├── QuizDialog.tsx
│ └── QuizView.tsx
└── index.ts
src/pages/lessons/a1/quizzes/ # ✅ Quiz pages
└── index.mdx
data/quizzes/ # ✅ Quiz data
├── a1/
│ └── alphabets.json
└── meta.json
```
## Benefits
- **Easy to find**: All feature code in one place
- **Easy to remove**: Delete one directory to remove entire feature
- **Easy to maintain**: Clear boundaries between features
- **Better for team collaboration**: Clear ownership and structure

View File

@ -1,103 +0,0 @@
---
id: rule-general-file-endings
alwaysApply: true
description: Files must end with exactly one newline character. No trailing newlines beyond the single required newline at the end of file content.
author: Himel Das
---
# File Endings
## Core Principle
All files must end with **exactly one newline character** after the content. No additional trailing newlines should be present.
## Rules
1. Files must end with exactly one newline character (`\n`)
2. Do not add multiple newlines at the end of files
3. Do not omit the final newline character
4. The newline should be the last character in the file
## Examples
### ✅ Correct
**Code file:**
```
// File content here
const example = "value";
```
**Markdown file:**
```
# Documentation Title
This is the content.
```
**Config file:**
```
key1=value1
key2=value2
```
**Documentation file:**
```
This is documentation content.
More content here.
```
All files end with exactly one newline after the last line.
### ❌ Incorrect
**Multiple newlines:**
```
// File content here
const example = "value";
```
```
# Documentation Title
This is the content.
```
File ends with multiple newlines (2+).
### ❌ Incorrect
**No newline:**
```
// File content here
const example = "value";
```
```
# Documentation Title
This is the content.
```
File ends with no newline character.
## Implementation
When creating or editing files:
- Ensure the file ends with exactly one newline character
- Remove any extra trailing newlines
- Add a single newline if the file is missing the final newline
## Remember
- One newline at the end of every file
- No more, no less
- This applies to all file types (code, config, documentation, etc.)

View File

@ -1,73 +0,0 @@
---
id: rule-general-file-organization
alwaysApply: true
description: Rules for consolidating related components into single files instead of splitting them. Defines when to consolidate vs split components based on coupling and domain.
author: Himel Das
---
# File Organization
## Consolidation Principle
**Keep related components in ONE file** instead of splitting into multiple files.
### ✅ DO - Consolidate Related Components
**Question Types** - All in one file:
```typescript
// ✅ Good: src/components/quiz/question-types.tsx
export function SingleChoice() { }
export function MultipleChoice() { }
export function FillBlank() { }
export function TrueFalse() { }
export function Matching() { }
export function QuestionRenderer() { }
```
**Views** - All in one file:
```typescript
// ✅ Good: src/components/quiz/views.tsx
export function QuizIntroView() { }
export function QuizActiveView() { }
export function QuizResultsView() { }
```
**Wrappers** - All in one file:
```typescript
// ✅ Good: src/components/quiz/wrappers.tsx
export function QuizDialogWrapper() { }
export function QuizPageWrapper() { }
```
### ❌ DON'T - Split Related Components
```typescript
// ❌ Bad: Multiple files for related components
src/components/quiz/question-types/
single-choice.tsx
multiple-choice.tsx
fill-blank.tsx
true-false.tsx
matching.tsx
question-renderer.tsx
```
## When to Split vs Consolidate
### ✅ CONSOLIDATE when:
- Components are used together (question types)
- Components share the same domain (views, wrappers)
- Components are tightly coupled
- Components have similar imports
### ✅ SPLIT when:
- Components are from different domains
- Components have very different dependencies
- Component files exceed ~300 lines (consider splitting)
## Benefits of Consolidation
- **Fewer imports**: Import all related components from one file
- **Easier to find**: Related code lives together
- **Less navigation**: No jumping between many files
- **Better cohesion**: Related functionality grouped logically

View File

@ -1,26 +0,0 @@
---
id: rule-general-libraries
alwaysApply: true
description: Rules for library selection - prefer popular, well-maintained libraries over custom code. Research and use battle-tested solutions before writing custom implementations.
author: Himel Das
---
# Libraries & Dependencies
## Library Selection
- Use popular, well-maintained libraries over custom code
- Choose the best/most popular library for each specific purpose
- Minimal custom implementation - utilize community solutions
- Research and use battle-tested solutions
## Before Writing Custom Code
1. Check if a popular library exists
2. Verify it's actively maintained
3. Confirm it's the best solution for the purpose
4. Only write custom code if no suitable library exists
## Examples
- Authentication → use established auth libraries
- Form validation → use popular validation libraries
- State management → use proven state libraries
- API clients → use well-known HTTP clients

View File

@ -1,23 +0,0 @@
---
id: rule-general-restrictions
alwaysApply: true
description: Restrictions and constraints - what not to do (inline styles, custom CSS, new UI libraries, large refactors) and what to do (minimal changes, follow patterns, reuse code).
author: Himel Das
---
# Restrictions
## Do NOT
- ❌ Add inline styles
- ❌ Create custom CSS files
- ❌ Install new UI libraries
- ❌ Use `style` prop
- ❌ Duplicate existing components
- ❌ Ignore project patterns
- ❌ Make large refactors
## Do
- ✅ Minimal changes only
- ✅ Follow existing patterns
- ✅ Check existing code first
- ✅ Reuse utilities and components

View File

@ -1,46 +0,0 @@
---
id: rule-meta-always-apply-all-rules
alwaysApply: true
description: Meta-rule ensuring all rules in .cursor/rules/ directory are always followed in every conversation and project. This rule takes precedence and ensures comprehensive rule compliance.
author: Himel Das
---
# Always Apply All Rules
## Core Principle
**Rules in the `.cursor/rules/` directory MUST be followed based on their `alwaysApply` setting:**
- Rules with `alwaysApply: true` MUST be followed in EVERY conversation and project
- Rules with `alwaysApply: false` should only be followed when relevant to the project context
## Rule Application
- Rules with `alwaysApply: true` in their frontmatter are automatically active in all conversations
- Rules with `alwaysApply: false` are applied only when relevant to the specific project context
- Rules are organized by category in subdirectories
- Each rule file contains specific guidelines that must be followed when applicable
- No rule should be ignored or bypassed unless explicitly overridden by a higher-priority rule
## Enforcement
- When implementing any feature or making any changes, verify compliance with ALL applicable rules
- Apply rules with `alwaysApply: true` unconditionally
- Apply rules with `alwaysApply: false` only when they match the project context (e.g., technology stack, project type, etc.)
- If rules conflict, prioritize more specific rules over general ones
- When in doubt, refer to the specific rule file for clarification
- Rules are cumulative - all applicable rules must be followed simultaneously
## Rule Discovery
- Check `.cursor/rules/` directory structure to find relevant rules
- Read rule files to understand specific requirements
- Rules are self-documenting with clear DO/DON'T patterns
## Priority
This meta-rule has the highest priority and ensures that:
- All rules with `alwaysApply: true` are discovered and applied in every conversation
- Rules with `alwaysApply: false` are applied when contextually relevant
- No rule is accidentally ignored when it should be active
- Consistent behavior across all projects and conversations

View File

@ -1,46 +0,0 @@
---
id: rule-meta-rule-creation
alwaysApply: true
description: Concise guidelines for creating rules and prompts with required frontmatter and optimization techniques
author: Himel Das
---
# Rule Creation
> **Note**: The author has named this technique **Equation-Based DRY Prompting (EBDP)**.
## Core Rules
### Frontmatter Format
```
---
id: rule-{category}-{filename-without-ext}
alwaysApply: true | false
description: concise description
author: Himel Das
---
```
**ID Pattern**: `rule-{category}-{filename-without-ext}` → `rule-general-file-organization` for `general/file-organization.mdc`
### Content Guidelines
Concise, generic, language-independent. Avoid project-specific details. Focus on **what** to do, not **how**. Use easy notation: `≤`, `≥`, `→`, `=`, `{A|B}`. Define constants at top if referenced `≥ 2` times. File format: `.mdc` with kebab-case names.
## Process
Check categories (fit existing if possible). Create frontmatter using pattern above. Write content following **Content Guidelines**. Define constants for values referenced `≥ 2` times. Optimize using reduction techniques.
## Constants Pattern
If value referenced `≥ 2` times, define at top:
```
## Constants
- **CONFIG_FILE**: `path/to/config.json` - Description
## Process
- Read from `CONFIG_FILE`
- Update `CONFIG_FILE`
```

View File

@ -1,38 +0,0 @@
---
id: rule-nextjs-routes
alwaysApply: true
description: Rules for route management - all URL routes must be defined as constants in @/lib/routes.ts, never hardcode URLs, use descriptive names and type safety.
author: Himel Das
---
# Routes & URLs
## Route Constants
- ALL URL routes MUST be defined as constants first
- Store route constants in `@/lib/routes.ts`
- NEVER hardcode URLs directly in components or API calls
## Pattern
```typescript
export const API_ROUTES = {
CATEGORY: {
ENDPOINT_NAME: '/api/category/endpoint',
}
} as const;
```
## Usage
```typescript
// ✅ Good
import { API_ROUTES } from '@/lib/routes';
fetch(API_ROUTES.GOOGLE.DRIVE_PROXY);
// ❌ Bad
fetch('/api/google/drive-proxy');
```
## Rules
- Define route constant before using it
- Use descriptive, uppercase names
- Group by feature/category
- Use `as const` for type safety

View File

@ -1,11 +0,0 @@
---
id: rule-python-code-formatting
alwaysApply: false
description: Blank lines between logical groups; full words for names; no comments for separation
author: Himel Das
globs: "**/*.py"
---
# Code Formatting
Insert blank lines between logical groups (validation → create → assign → return). Separate fetch, processing, validation, and return blocks. Use blank lines only; do not add comments purely for visual separation. Use full words for variables and identifiers (e.g. `customer`, `order_id`, `item_count`), not abbreviations (`c`, `o`, `n`).

View File

@ -1,32 +0,0 @@
---
id: rule-python-virtual-environment
alwaysApply: true
description: Rules for using Python virtual environments - check requirements.txt for installed libraries and use the existing virtual environment directory.
author: Himel Das
---
# Virtual Environment
## Virtual Environment Location
- Check for existing virtual environment directories using conventional names (`.venv`, `venv`, `env`, `virtualenv`)
- Use the existing virtual environment directory if found
- Do not create new virtual environments
- Do not modify the existing virtual environment location
## Installed Libraries
- Check `requirements.txt` to find libraries that are already installed
- Before installing new libraries, verify if they are already listed in `requirements.txt`
- Only install libraries that are not already in `requirements.txt`
- When installing new libraries, update `requirements.txt` accordingly
## Rules
- ✅ Use the existing virtual environment directory
- ✅ Check for conventional virtual environment directory names before creating new ones
- ✅ Check `requirements.txt` before installing dependencies
- ✅ Update `requirements.txt` when adding new dependencies
- ❌ Do not create new virtual environments if one already exists
- ❌ Do not install libraries that are already in `requirements.txt`
- ❌ Do not modify the existing virtual environment location

View File

@ -1,55 +0,0 @@
---
id: rule-react-components
alwaysApply: true
description: Rules for component usage - which component libraries are allowed (shadcn/ui, Aceternity, Kibo, Magic UI, etc.), reuse over recreation, table implementation standards, and component modularization for both new features and existing components.
author: Himel Das
---
# Component Usage
## Allowed Sources
Use components ONLY from:
1. shadcn/ui components
2. `@/components/ui/`
3. `@/components/ui/aceternity/`
4. `@/components/ui/kibo-ui/`
5. `@/components/ui/magicui/`
6. `@/components/ui/motion-primitives/`
7. `@/components/ui/origin-ui/`
8. `@/components/ui/skiper-ui/`
## Rules
- Check existing components before creating new ones
- Reuse over recreate
- Do NOT install new component libraries
## Table Implementation
- Use `@tanstack/react-table` library (TanStack Table) for all table implementations
- Reference `src/components/vocabulary-table.tsx` for configuration patterns
- Default page size: 40, with options for 80 and 100
- Include pagination, sorting, and filtering capabilities
## Component Modularization
When creating or updating components (including new features), group related components together in single files to minimize file count and maintain ease of use. This applies to both breaking down existing large components and building new feature components from scratch.
### ✅ DO - Group Related Components
- Group components that work together in the same file
- Keep related UI components together (e.g., list and list item components)
- Group layout components together (e.g., header, footer, setup screens)
- Keep domain-specific components together
### ❌ DON'T - Create Too Many Files
- Don't create separate files for each small component
- Don't split related components that are used together
- Don't create unnecessary subdirectories for component organization
### Principles
1. **Group by Domain**: Components that work together should be in the same file
2. **Keep Main Component Simple**: Main component should focus on state management and orchestration, using modular components
3. **Minimize Files**: Prefer fewer files with related components over many small files
4. **Ease of Use First**: Don't break components if it makes them harder to use or maintain
5. **Don't Over-Modularize**: If breaking something apart makes it complicated to use, keep it together

View File

@ -1,190 +0,0 @@
---
id: rule-swift-project-organization
alwaysApply: true
description: Organize code with foundational/application separation and extract reusable components from context-specific wrappers
author: Himel Das
---
# Swift Project Organization
## Core Principle
Separate foundational/reusable code from application-specific code:
- **Foundational/Reusable Code** → Reusable across projects
- **Application-Specific Code** → Specific to this application
## Architecture Pattern
Follow MVVM (Model-View-ViewModel) pattern for clear separation of concerns.
## Type Definitions
### Models
Pure data structures representing application entities. Contain only data properties, no business logic. Use for data structures, entities from external sources, data transfer objects. Do not include business logic, operations, or state management.
### Views
Presentation layer components that render user interface. Contain only presentation logic, observe ViewModels for state, delegate user actions to ViewModels. Use for UI components, displaying data, visual interactions. Do not contain business logic, access services directly, or manage complex state.
### ViewModels
State management and business logic coordination for views. Observable for reactive updates, coordinate with services, transform models for presentation. Use for managing view state, coordinating data sources, business logic. Do not reference specific view implementations or contain presentation logic.
### Services
Stateless utility classes that perform operations and data management. Stateless operations, reusable across features. Use for data storage, file operations, network requests, utility functions. Do not manage resource lifecycle, maintain state, or coordinate multiple services.
### Managers
Stateful classes that manage lifecycle and coordinate resources. Maintain state for resources, manage object lifecycle, coordinate services. Use for window lifecycle, resource management, coordinating services. Do not perform stateless data operations or contain business logic.
## Directory Structure
### App-Level Organization
Place app-level code at the top level of the application directory:
- **Models** - Data structures used across multiple features
- **ViewModels** - State management for app-level views
- **Views** - App-level views and components
- **Services** - App-level services and utilities
These are shared across features and not specific to any single feature.
### Feature-Level Organization
All features are organized under the `Features/` directory. Every feature must follow MVVM pattern with clear separation of concerns. Bundle all feature-specific code within feature directories:
- **Features/FeatureName/Models/** - Data structures specific to the feature
- **Features/FeatureName/ViewModels/** - State management and business logic for the feature
- **Features/FeatureName/Views/** - Views specific to the feature
- **Features/FeatureName/Services/** - Services and utilities specific to the feature
- **Features/FeatureName/Managers/** - Lifecycle managers and state coordinators specific to the feature
All code related to a feature must stay within its feature directory. Each feature is self-contained with its own Models, ViewModels, Views, Services, and Managers following MVVM architecture.
## Feature Structure Example
Every feature follows this standard structure:
```
App/
├── Features/
│ └── FeatureName/
│ ├── Models/
│ │ └── FeatureModel.swift # Feature-specific data structures
│ ├── ViewModels/
│ │ └── FeatureViewModel.swift # Feature business logic and state
│ ├── Views/
│ │ └── FeatureView.swift # Feature presentation layer
│ ├── Services/
│ │ └── FeatureService.swift # Feature-specific services
│ └── Managers/
│ └── FeatureManager.swift # Feature-specific lifecycle managers
```
**Key Principles:**
- Each feature is self-contained with Models, ViewModels, Views, Services, Managers
- ViewModels handle business logic, Views handle presentation, Models are pure data
- Services are stateless operations, Managers handle lifecycle
## Component Extraction Pattern
### Core Principle
Never embed component-specific UI logic directly in context wrappers. Always extract reusable UI components into separate files so they can be used in any context (window, popover, sheet, etc.).
**Two-Layer Architecture:**
1. **Core Component** - All UI logic and state management, context-agnostic, accepts optional dimensions
2. **Context Wrapper** - Minimal wrapper for context-specific lifecycle, sizing, and preferences
**Benefits:** Reusable across contexts (popover, window, sheet), clear separation of concerns, flexible sizing, single source of truth for UI logic
### Shared Component Extraction
When the same UI components appear in multiple places (e.g., settings tab and setup wizard), extract them into shared reusable components. Create dedicated files for shared components within the feature's Views directory. Pass data and callbacks through bindings and closures to maintain flexibility. This eliminates code duplication and ensures consistent behavior across all usages.
## Rules
### ✅ DO
#### MVVM
- Use ViewModels for state management and business logic
- Make ViewModels conform to ObservableObject
- Use published properties in ViewModels for reactive updates
- Keep views thin with only presentation logic
- Delegate user actions from views to ViewModels
- Place app-level models in app-level Models directory
- Place feature-specific models in feature Models directory
- Place app-level ViewModels in app-level ViewModels directory
- Place feature-specific ViewModels in feature ViewModels directory
- Make services and utilities reusable across ViewModels
#### Component Extraction
- **Always extract** reusable UI components into separate files
- Create minimal context wrappers that only handle context-specific concerns
- Make components accept optional dimensions for flexibility
- Keep all UI logic and state management in ViewModels
- Extract duplicate UI sections into shared components when used in multiple places
- Create dedicated files for shared components within the feature's Views directory
- Use bindings and closures to pass data and actions to shared components
#### Organization
- Place app-level models, views, ViewModels, and services at the top level
- Organize all features under the `Features/` directory
- Bundle all feature-specific code (models, views, ViewModels, services, managers) within feature directories under `Features/`
- Keep all code for a feature together in its feature directory
- Follow MVVM pattern for every feature with ViewModels and Views subdirectories
- Ensure each feature has clear separation: Models, ViewModels, Views, Services, Managers
- Use Services for data operations and utilities
- Use Managers for lifecycle and state coordination
- Place reusable utilities in foundational directories
- Place application-specific utilities in application directories
- Keep foundational code independent of application code
- Make foundational utilities importable by application code
- Keep resources at the appropriate level
### ❌ DON'T
#### MVVM
- Put business logic in views
- Access services directly from views
- Reference specific views in ViewModels
- Mix model and ViewModel responsibilities
- Use State in views for complex state (use ViewModels instead)
#### Component Extraction
- **Never embed** component-specific UI logic directly in context wrappers
- **Never write** business logic in context wrappers (popover, window, sheet)
- Create separate components for each context when extraction is possible
- Hardcode context-specific configuration in reusable components
- Do not duplicate UI code across multiple views when shared components can be extracted
- Do not mix shared and context-specific logic in the same component
#### Organization
- Place feature-specific code at the app level (must be under `Features/`)
- Split feature code across multiple locations
- Mix app-level and feature-specific code in the same directory
- Place app-level code inside feature directories
- Place features directly under `App/` instead of under `Features/`
- Create features without ViewModels or Views subdirectories
- Mix business logic in Views instead of ViewModels
- Share ViewModels or Views across multiple features
- Put lifecycle managers in Services directory (use Managers directory instead)
- Put data storage services in Managers directory (use Services directory instead)
- Mix foundational and application-specific code
- Place application-specific logic in foundational utilities
- Place reusable utilities in application directories
- Create dependencies from foundational code to application code
- Include application-specific types or data in foundational code
## Benefits
- **Reusability**: Foundational code can be extracted for other projects
- **Clear boundaries**: Easy to identify what's reusable vs application-specific
- **Maintainability**: Clear separation makes code easier to understand and modify
- **Template-friendly**: Foundation code serves as a reusable template
- **Scalability**: Easy to add new features without affecting foundational code
- **Component flexibility**: Core components can be reused in multiple contexts without modification

View File

@ -1,24 +0,0 @@
---
id: rule-tailwindcss-styling
alwaysApply: true
description: Rules for styling - use Tailwind CSS only, no inline styles, use CSS variables for colors, monochromic design pattern, and button icon spacing guidelines.
author: Himel Das
---
# Styling
## Tailwind Only
- Use Tailwind CSS classes ONLY
- NO inline styles
- NO custom CSS unless absolutely necessary
- Use `cn()` from `@/lib/utils` for class concatenation
## Colors
- Use CSS variables: `hsl(var(--color-name))`
- Follow theme in `tailwind.config.js`
- Use monochromic design pattern
## Button Icon Spacing
- DO NOT add `mr-2` or similar margin classes to icons inside buttons
- Button component has built-in spacing between icon and text
- Let the Button component handle spacing automatically

View File

@ -1,61 +0,0 @@
---
id: rule-typescript-code-patterns
alwaysApply: true
description: Rules for component structure, import patterns using @/ path aliases (never relative paths), import ordering, and TypeScript conventions.
author: Himel Das
---
# Code Patterns
## Component Structure
```typescript
import React from "react";
interface ComponentProps {
children: React.ReactNode;
}
export function Component({ children }: ComponentProps) {
return <div>{children}</div>;
}
export default Component;
```
## Imports
### Path Aliases
- **ALWAYS use `@/` path alias, NEVER use relative paths**
- Use `@/components/...` instead of `../components/...`
- Use `@/lib/...` instead of `../../lib/...`
- Use `@/hooks/...` instead of `../../../hooks/...`
- **Even for same-directory imports, use `@/` NOT `./`**
- Use `@/components/quiz/question-types/single-choice` instead of `./single-choice`
### Import Order
- React/external → internal components → types → utilities
- Example: `import React from 'react'; import { Button } from '@/components/ui/button'; import { MyType } from '@/types';`
### Examples
✅ **Correct:**
```typescript
import { Button } from '@/components/ui/button';
import { MyType } from '@/components/quiz/types';
import { helper } from '@/lib/utils';
import { SingleChoice } from '@/components/quiz/question-types/single-choice';
```
❌ **Wrong:**
```typescript
import { Button } from '../../../components/ui/button';
import { MyType } from '../types';
import { helper } from '../../lib/utils';
import { SingleChoice } from './single-choice'; // Even same-directory should use @/
```
## General
- TypeScript for all files
- Functional components with hooks
- Add `displayName` to forwarded refs
- Use `class-variance-authority` for variants

View File

@ -1,11 +0,0 @@
---
alwaysApply: true
description: Always check and use available skills
---
# Use Available Skills
## Behavior
- Before starting any task, check .cursor/skills/ for relevant SKILL.md
- If a matching skill exists, follow it exactly
- Always prefer skill instructions over general knowledge

View File

@ -1,87 +0,0 @@
---
name: accessibility-auditing
description: Use Cursor's browser aria snapshots to audit a page for accessibility issues — missing labels, broken tab order, contrast, and ARIA misuse.
user-invocable: true
---
# Accessibility Auditing
Audit a web page for accessibility issues using Cursor's built-in browser without external tools.
## Workflow
### 1. Open the Page
Use `browser_navigate` to open the target URL.
### 2. Capture the Accessibility Tree
Use `browser_snapshot` — this returns the aria/accessibility tree of the page. This is the same tree that screen readers use.
### 3. Audit the Tree
Check for these issues:
**Missing Labels**
- `button` elements with no accessible name (no text, no `aria-label`)
- `img` elements with no `alt` text
- `input` elements with no associated `label` or `aria-label`
- `a` (link) elements with no text content
- Icon-only buttons missing `aria-label`
**Semantic HTML**
- Clickable `div` or `span` elements → should be `button` or `a`
- Missing `nav`, `main`, `header`, `footer` landmarks
- Headings that skip levels (h1 → h3)
- Lists that aren't using `ul`/`ol`/`li`
**Keyboard Navigation**
- Interactive elements missing from tab order
- Custom widgets without `role` and keyboard handlers
- Focus traps in modals (should trap focus, but also allow Escape to close)
- Skip-to-content link missing
**ARIA Issues**
- `aria-hidden="true"` on focusable elements
- Invalid `role` values
- `aria-expanded` without corresponding collapsible content
- `aria-controls` pointing to non-existent IDs
**Contrast** (use screenshot for visual check)
- Light gray text on white backgrounds
- Placeholder text that's too faint
- Disabled states that are indistinguishable
### 4. Test Keyboard Navigation
Use `browser_press` to simulate Tab key presses and verify:
- Every interactive element receives focus
- Focus order is logical (top-to-bottom, left-to-right)
- Focus is visible (focus ring or outline)
- Escape closes modals/dropdowns
### 5. Report
```
Accessibility Audit:
Critical:
- 3 buttons with no accessible name (header icons)
- Login form inputs missing labels
Warnings:
- Heading levels skip from h1 to h3
- No skip-to-content link
- 2 clickable divs should be buttons
Passed:
- All images have alt text
- Landmarks present (nav, main, footer)
- Focus order is logical
```
### 6. Fix
For each issue, apply the fix in the source code. Common fixes:
- Add `aria-label="Close"` to icon buttons
- Wrap inputs in `<label>` or add `htmlFor`
- Change `<div onClick>` to `<button>`
- Add `alt` text to images
- Fix heading hierarchy

View File

@ -1,67 +0,0 @@
---
name: adding-analytics
description: Add PostHog analytics to a web application, including event tracking, page views, feature flags, and session replay.
---
# Add Analytics (PostHog)
Use this skill when the user asks to add analytics, event tracking, page views, feature flags, or session replay to a web application.
## Steps
1. **Detect the framework** — check for `next.config.*`, `vite.config.*`, `package.json` scripts, or `index.html` to determine if this is Next.js, React (Vite/CRA), Vue, Svelte, or plain HTML.
2. **Install the SDK**
- Next.js / React: `npm install posthog-js`
- Next.js (server-side): `npm install posthog-js posthog-node`
- Python: `pip install posthog`
- Node.js backend: `npm install posthog-node`
3. **Create a provider / init module**
- For Next.js App Router, create `app/providers.tsx`:
```tsx
"use client";
import posthog from "posthog-js";
import { PostHogProvider as PHProvider } from "posthog-js/react";
import { useEffect } from "react";
export function PostHogProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST ?? "https://us.i.posthog.com",
capture_pageview: false, // we capture manually for SPAs
});
}, []);
return <PHProvider client={posthog}>{children}</PHProvider>;
}
```
- Wrap `{children}` in the root layout with `<PostHogProvider>`.
- For Pages Router, init in `_app.tsx` inside a `useEffect`.
4. **Add page-view tracking** — for SPAs, create a component that calls `posthog.capture('$pageview')` on route change using the framework's router events.
5. **Add `.env` variables** — prompt the user for their PostHog project API key and host:
```
NEXT_PUBLIC_POSTHOG_KEY=phc_...
NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com
```
Add these keys to `.env.example` as well.
6. **Add custom events** — if the user specifies events to track (e.g. sign-up, purchase), add `posthog.capture("event_name", { ...properties })` calls in the relevant handlers.
7. **Feature flags (optional)** — if requested, show how to use `posthog.isFeatureEnabled("flag-name")` or the `useFeatureFlagEnabled` hook.
8. **Session replay (optional)** — enable by adding `session_recording: { maskAllInputs: false }` to the init config if requested.
## Notes
- Never hardcode API keys — always use environment variables.
- Add `posthog-js` to the Content Security Policy if the project has one.
- For monorepos, install in the package that renders the UI, not the root.

View File

@ -1,53 +0,0 @@
---
name: adding-api-docs
description: Generate OpenAPI/Swagger documentation for an API, including endpoint schemas, request/response types, and interactive docs UI.
---
# Add API Documentation (OpenAPI)
Use this skill when the user asks to add API docs, Swagger, OpenAPI spec, or generate endpoint documentation.
## Steps
1. **Detect the API framework** — check for Express, Fastify, Next.js API routes, Hono, Django REST Framework, FastAPI, etc.
2. **For Node.js/Express** — install `swagger-jsdoc` and `swagger-ui-express`:
```bash
npm install swagger-jsdoc swagger-ui-express
npm install -D @types/swagger-jsdoc @types/swagger-ui-express
```
Create the OpenAPI spec from JSDoc annotations on route handlers:
```ts
/**
* @openapi
* /api/users:
* get:
* summary: List all users
* responses:
* 200:
* description: A list of users
*/
```
3. **For Next.js API routes** — create an `openapi.json` file manually or use `next-swagger-doc` to generate from route handlers. Serve the spec at `/api/docs`.
4. **For FastAPI (Python)** — docs are built-in at `/docs` (Swagger UI) and `/redoc`. Ensure Pydantic models are used for request/response types so schemas are auto-generated.
5. **Add interactive docs UI** — serve Swagger UI at a `/docs` route, or use Scalar/Redoc for a modern alternative:
```bash
npm install @scalar/express-api-reference
```
6. **Define schemas** — create Zod schemas (or JSON Schema) for request bodies and responses, then reference them in the OpenAPI spec. For TypeScript projects, use `zod-to-openapi` to generate schemas from existing Zod validators.
7. **Add authentication documentation** — document the auth scheme (Bearer token, API key, OAuth2) in the OpenAPI `securitySchemes` section.
## Notes
- Keep the spec in sync with the actual API — generate from code when possible rather than maintaining a separate YAML file.
- Add example values to schemas for better developer experience.
- Version the API docs alongside the code.

View File

@ -1,76 +0,0 @@
---
name: adding-auth
description: Add authentication to a web application using NextAuth.js (Auth.js), including OAuth providers, session management, and protected routes.
---
# Add Authentication (Auth.js)
Use this skill when the user asks to add authentication, login, sign-up, OAuth, or session management.
## Steps
1. **Install dependencies**
```bash
npm install next-auth@beta
```
2. **Generate an auth secret**
```bash
npx auth secret
```
This adds `AUTH_SECRET` to `.env.local`.
3. **Create the auth config** — create `auth.ts` in the project root:
```ts
import NextAuth from "next-auth";
import GitHub from "next-auth/providers/github";
import Google from "next-auth/providers/google";
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [GitHub, Google],
});
```
4. **Add the route handler** — create `app/api/auth/[...nextauth]/route.ts`:
```ts
import { handlers } from "@/auth";
export const { GET, POST } = handlers;
```
5. **Add environment variables** for each provider:
```
AUTH_SECRET=...
AUTH_GITHUB_ID=...
AUTH_GITHUB_SECRET=...
AUTH_GOOGLE_ID=...
AUTH_GOOGLE_SECRET=...
```
6. **Add sign-in/sign-out UI** — create components that call the `signIn` and `signOut` server actions, or use `<Link href="/api/auth/signin">`.
7. **Protect routes** — use the `auth()` function in server components or middleware:
```ts
import { auth } from "@/auth";
export default async function ProtectedPage() {
const session = await auth();
if (!session) redirect("/api/auth/signin");
return <div>Welcome {session.user?.name}</div>;
}
```
8. **Add database adapter (optional)** — if the user needs persistent sessions or user records, install a database adapter (e.g. `@auth/drizzle-adapter`, `@auth/prisma-adapter`) and configure it in the auth config.
## Notes
- Auth.js v5 works with Next.js App Router and Server Actions natively.
- For Pages Router, use `getServerSession` in `getServerSideProps` and `useSession` on the client.
- Add `NEXTAUTH_URL` for production deployments.
- Store minimal user data in the session; fetch full profiles from the database when needed.

View File

@ -1,93 +0,0 @@
---
name: adding-docker
description: Dockerize an application with a production-ready Dockerfile, docker-compose setup, and .dockerignore.
---
# Add Docker
Use this skill when the user asks to dockerize, containerize, or add Docker support to an application.
## Steps
1. **Detect the runtime** — inspect `package.json`, `requirements.txt`, `go.mod`, `Cargo.toml`, etc. to determine the language and runtime.
2. **Create a multi-stage `Dockerfile`**
For Node.js (example):
```dockerfile
FROM node:20-alpine AS base
FROM base AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
FROM base AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=deps /app/node_modules ./node_modules
COPY --from=build /app/.next ./.next
COPY --from=build /app/public ./public
COPY --from=build /app/package.json ./
EXPOSE 3000
CMD ["npm", "start"]
```
Adapt for the detected framework — adjust the build output directory, entry command, and base image.
3. **Create `.dockerignore`**
```
node_modules
.next
.git
.env*
*.md
```
4. **Create `docker-compose.yml`** (if the app has dependencies like a database or Redis):
```yaml
services:
app:
build: .
ports:
- "3000:3000"
env_file: .env
depends_on:
- db
db:
image: postgres:16-alpine
environment:
POSTGRES_DB: app
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:
```
5. **Add npm scripts** (optional)
```json
{
"docker:build": "docker build -t myapp .",
"docker:run": "docker compose up"
}
```
## Notes
- Use Alpine-based images to minimize image size.
- Never copy `.env` files into the image — use `env_file` or runtime injection.
- For monorepos, use a `.dockerignore` that excludes sibling packages not needed by the target app.
- Add a `HEALTHCHECK` instruction for production deployments.

View File

@ -1,76 +0,0 @@
---
name: adding-e2e-tests
description: Set up Playwright end-to-end testing in a project, including test configuration, example tests, and CI integration.
---
# Add E2E Tests (Playwright)
Use this skill when the user asks to add end-to-end tests, browser tests, integration tests, or set up Playwright.
## Steps
1. **Install Playwright**
```bash
npm init playwright@latest
```
This creates `playwright.config.ts`, a `tests/` directory, and installs browsers. If the project already has a test runner, install manually:
```bash
npm install -D @playwright/test
npx playwright install
```
2. **Configure `playwright.config.ts`**
- Set `baseURL` to the local dev server URL (e.g. `http://localhost:3000`).
- Configure `webServer` to start the dev server automatically:
```ts
webServer: {
command: "npm run dev",
url: "http://localhost:3000",
reuseExistingServer: !process.env.CI,
},
```
- Enable only chromium for local dev speed; enable all browsers in CI.
3. **Create a smoke test** — write a basic test that verifies the app loads:
```ts
import { test, expect } from "@playwright/test";
test("homepage loads", async ({ page }) => {
await page.goto("/");
await expect(page).toHaveTitle(/.+/);
});
```
4. **Add page object pattern (optional)** — for larger apps, create a `tests/pages/` directory with page objects that encapsulate selectors and actions.
5. **Add npm scripts**
```json
{
"test:e2e": "playwright test",
"test:e2e:ui": "playwright test --ui"
}
```
6. **Add to `.gitignore`**
```
test-results/
playwright-report/
blob-report/
```
7. **CI integration** — add a GitHub Actions step that runs `npx playwright install --with-deps` then `npm run test:e2e`. Use the official `actions/upload-artifact` to save the HTML report on failure.
## Notes
- Use `data-testid` attributes for selectors instead of CSS classes.
- Use `test.describe` to group related tests.
- Run `npx playwright codegen` to record tests interactively.

View File

@ -1,58 +0,0 @@
---
name: adding-error-tracking
description: Add Sentry error tracking, performance monitoring, and source maps to a web application.
---
# Add Error Tracking (Sentry)
Use this skill when the user asks to add error tracking, crash reporting, exception monitoring, or performance tracing.
## Steps
1. **Detect the framework** — check `package.json`, config files, and directory structure to determine the stack (Next.js, React, Node.js, Python/Django/Flask, etc.).
2. **Install the SDK**
- Next.js: `npx @sentry/wizard@latest -i nextjs`
- React (Vite): `npm install @sentry/react`
- Node.js: `npm install @sentry/node`
- Python: `pip install sentry-sdk`
3. **Initialize Sentry**
- For Next.js, the wizard creates `sentry.client.config.ts`, `sentry.server.config.ts`, and `sentry.edge.config.ts`. Verify they exist and contain the DSN.
- For React (Vite), init in `main.tsx`:
```tsx
import * as Sentry from "@sentry/react";
Sentry.init({
dsn: import.meta.env.VITE_SENTRY_DSN,
integrations: [Sentry.browserTracingIntegration()],
tracesSampleRate: 1.0,
});
```
- For Node.js, init at the very top of the entry file before any other imports.
4. **Add environment variables**
```
NEXT_PUBLIC_SENTRY_DSN=https://...@sentry.io/...
SENTRY_AUTH_TOKEN=sntrys_...
SENTRY_ORG=your-org
SENTRY_PROJECT=your-project
```
5. **Add error boundary** — wrap the app (or critical subtrees) with `Sentry.ErrorBoundary` and a fallback UI.
6. **Source maps** — for production builds, configure the Sentry webpack/vite plugin to upload source maps. For Next.js, this is handled by `withSentryConfig` in `next.config.js`.
7. **Test the integration** — add a temporary button that throws an error to verify events appear in the Sentry dashboard.
## Notes
- Set `tracesSampleRate` to a lower value (e.g. `0.1`) in production to control costs.
- Add `sentry.properties` and `.sentryclirc` to `.gitignore`.
- Never commit `SENTRY_AUTH_TOKEN`.

View File

@ -1,76 +0,0 @@
---
name: adding-feature-flags
description: Add feature flags to an application for gradual rollouts, A/B testing, and kill switches using PostHog, LaunchDarkly, or a simple local implementation.
---
# Add Feature Flags
Use this skill when the user asks to add feature flags, feature toggles, gradual rollouts, or A/B testing.
## Option A: PostHog Feature Flags (Recommended)
1. **Install PostHog** if not already present:
```bash
npm install posthog-js
```
2. **Use feature flags in code**:
```tsx
import { useFeatureFlagEnabled } from "posthog-js/react";
function MyComponent() {
const showNewFeature = useFeatureFlagEnabled("new-checkout-flow");
if (showNewFeature) return <NewCheckout />;
return <OldCheckout />;
}
```
3. **Server-side evaluation** — for server components or API routes:
```ts
import { PostHog } from "posthog-node";
const posthog = new PostHog(process.env.POSTHOG_API_KEY!);
const isEnabled = await posthog.isFeatureEnabled("new-checkout-flow", userId);
```
4. **Create flags in the PostHog dashboard** — set up targeting rules based on user properties, percentage rollouts, or cohorts.
## Option B: Simple Local Feature Flags
For projects that don't need a third-party service:
1. **Create a flags config**`lib/feature-flags.ts`:
```ts
export const FLAGS = {
NEW_CHECKOUT: process.env.NEXT_PUBLIC_FF_NEW_CHECKOUT === "true",
DARK_MODE: process.env.NEXT_PUBLIC_FF_DARK_MODE === "true",
} as const;
```
2. **Use in components**:
```tsx
import { FLAGS } from "@/lib/feature-flags";
function App() {
return FLAGS.NEW_CHECKOUT ? <NewCheckout /> : <OldCheckout />;
}
```
3. **Add env vars** — add flags to `.env` and `.env.example`:
```
NEXT_PUBLIC_FF_NEW_CHECKOUT=false
NEXT_PUBLIC_FF_DARK_MODE=true
```
## Notes
- Use feature flags for all user-facing changes during rollout, not just experiments.
- Clean up stale flags — remove the flag and the old code path once a feature is fully rolled out.
- For server-side flags, cache the evaluation result to avoid per-request API calls.
- Name flags descriptively: `new-checkout-flow` not `flag-1`.

View File

@ -1,65 +0,0 @@
---
name: adding-stripe
description: Integrate Stripe payments into a web application, including checkout sessions, webhooks, and customer portal.
---
# Add Stripe Payments
Use this skill when the user asks to add payments, billing, subscriptions, or Stripe integration.
## Steps
1. **Install the SDK**
```bash
npm install stripe @stripe/stripe-js
```
2. **Add environment variables**
```
STRIPE_SECRET_KEY=sk_test_...
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
```
3. **Create a Stripe client module** — create `lib/stripe.ts`:
```ts
import Stripe from "stripe";
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: "2024-12-18.acacia",
});
```
4. **Create a checkout API route** — create an endpoint that creates a Stripe Checkout session:
```ts
const session = await stripe.checkout.sessions.create({
mode: "subscription", // or "payment" for one-time
payment_method_types: ["card"],
line_items: [{ price: priceId, quantity: 1 }],
success_url: `${origin}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${origin}/pricing`,
customer_email: userEmail,
});
return redirect(session.url!);
```
5. **Create a webhook handler** — create a `POST` endpoint at `/api/webhooks/stripe`:
- Verify the webhook signature using `stripe.webhooks.constructEvent`.
- Handle key events: `checkout.session.completed`, `customer.subscription.updated`, `customer.subscription.deleted`, `invoice.payment_failed`.
- Update your database with the subscription status.
6. **Add customer portal (optional)** — create an endpoint that redirects to `stripe.billingPortal.sessions.create` so users can manage their subscription.
7. **Add pricing page UI** — create a pricing page with plan cards that call the checkout API route.
## Notes
- Always verify webhook signatures — never trust unverified payloads.
- Use Stripe CLI (`stripe listen --forward-to localhost:3000/api/webhooks/stripe`) for local webhook testing.
- Store the Stripe customer ID in your user database to avoid creating duplicate customers.
- Use `stripe.prices.list` to fetch prices dynamically instead of hardcoding them.

View File

@ -1,72 +0,0 @@
---
name: api-smoke-testing
description: Start the dev server, discover API routes from the codebase, hit every endpoint, and report which ones return errors.
user-invocable: true
---
# API Smoke Testing
Verify all API endpoints return healthy responses by combining codebase analysis with HTTP requests.
## Workflow
### 1. Discover Routes
Search the codebase for API route definitions:
**Next.js (App Router):** `app/api/**/route.ts`
**Next.js (Pages Router):** `pages/api/**/*.ts`
**Express:** Look for `app.get(`, `app.post(`, `router.get(`, etc.
**Django:** Look for `urlpatterns` in `urls.py`
**FastAPI:** Look for `@app.get(`, `@app.post(`, decorators
**Rails:** Look for `routes.rb`
Build a list of endpoints with their HTTP methods.
### 2. Ensure Server is Running
Check terminal files for a running dev server. If none found, start one.
### 3. Hit Every Endpoint
For each route:
```bash
curl -s -o /dev/null -w "%{http_code}" -X <METHOD> http://localhost:<PORT><PATH>
```
For endpoints that require a body (POST/PUT/PATCH), send a minimal valid JSON:
```bash
curl -s -o /dev/null -w "%{http_code}" -X POST http://localhost:<PORT><PATH> \
-H "Content-Type: application/json" \
-d '{}'
```
### 4. Classify Results
| Status | Meaning |
|--------|---------|
| 200-299 | OK |
| 301/302 | Redirect (OK) |
| 400 | Bad request (expected for empty POST bodies) |
| 401/403 | Auth required (expected for protected routes) |
| 404 | Route not found (BUG — route exists in code but not served) |
| 500 | Server error (BUG) |
| 000/timeout | Server not responding (BUG) |
### 5. Report
```
API Smoke Test Results:
Tested: 15 endpoints
Passed: 12
Auth required: 2 (GET /api/user, POST /api/settings)
Errors:
500 — POST /api/webhooks/stripe (TypeError: Cannot read property 'id' of undefined)
404 — GET /api/v2/health (route defined but not mounted)
```
### 6. Fix Errors
For 500 errors, read the terminal output for the stack trace and fix the root cause. For 404s, check that the route file is in the correct location and properly exported.

View File

@ -1,95 +0,0 @@
---
name: architecture-decision-records
description: Document technical decisions as Architecture Decision Records (ADRs) with context, options considered, and rationale.
user-invocable: true
---
# Architecture Decision Records
Document significant technical decisions so future you (and your team) understands why choices were made.
## When to Write an ADR
Write one when you're making a decision that:
- Is hard to reverse later
- Affects multiple parts of the system
- Involves tradeoffs between valid options
- Will be questioned by someone in 6 months
Examples: choosing a database, adopting a framework, changing auth strategy, restructuring the API, adding a build tool.
## Template
Create files in `docs/decisions/` (or `adr/`) with sequential numbering:
```markdown
# ADR-001: Use PostgreSQL for primary database
## Status
Accepted | Proposed | Deprecated | Superseded by ADR-XXX
## Date
2026-04-10
## Context
What is the problem or situation that requires a decision?
Include constraints, requirements, and forces at play.
## Options Considered
### Option A: PostgreSQL
- Pros: ACID compliance, JSON support, mature ecosystem, free
- Cons: Requires managing connections, vertical scaling limits
### Option B: MongoDB
- Pros: Flexible schema, horizontal scaling
- Cons: No transactions across collections, eventual consistency issues
### Option C: PlanetScale (MySQL)
- Pros: Serverless, branching, managed
- Cons: Vendor lock-in, no foreign keys in their branching model
## Decision
We chose **PostgreSQL** because:
1. Our data is relational — users, teams, projects with clear relationships
2. We need ACID transactions for billing operations
3. JSON columns give us schema flexibility where needed
4. Prisma/Drizzle have excellent Postgres support
## Consequences
- We need to manage connection pooling (use PgBouncer or Prisma's built-in pool)
- Migrations must be backwards-compatible for zero-downtime deploys
- We accept vertical scaling limits and will shard later if needed
```
## Workflow
1. **Identify** the decision being made
2. **Research** the options (at least 2-3 alternatives)
3. **Write** the ADR using the template
4. **Review** with the team (PR or discussion)
5. **Merge** as accepted
6. **Reference** from code comments when relevant: `// See ADR-001`
## File Naming
```
docs/decisions/
├── 001-use-postgresql.md
├── 002-adopt-trpc-over-rest.md
├── 003-switch-to-pnpm.md
└── template.md
```
## Tips
- Keep ADRs short — 1-2 pages max
- Write them in the present tense ("We choose X" not "We chose X")
- It's OK to write an ADR after the fact if you forgot to write one during the decision
- Superseded ADRs should link to their replacement, not be deleted
- ADRs are not design docs — they capture the decision, not the full design

View File

@ -1,48 +0,0 @@
---
name: auditing-performance
description: Audit and optimize application performance, including bundle size, rendering, database queries, and Core Web Vitals.
---
# Performance Audit
Use this skill when the user asks to optimize performance, reduce load times, fix slow pages, or audit Core Web Vitals.
## Steps
1. **Analyze bundle size**
- Run `npx @next/bundle-analyzer` (Next.js) or `npx vite-bundle-visualizer` (Vite) to identify large dependencies.
- Look for large libraries that could be replaced with lighter alternatives (e.g. `moment``date-fns`, `lodash` → individual imports or native methods).
- Check for duplicated dependencies in the bundle.
- Verify tree-shaking is working (no barrel file re-exports pulling in unused code).
2. **Audit rendering performance**
- Identify components that re-render unnecessarily — look for inline object/array/function creation in JSX props.
- Check for expensive computations in render paths that should use `useMemo`.
- Verify lists use proper `key` props (not array index for dynamic lists).
- Look for layout thrashing (reading DOM measurements then writing styles in a loop).
3. **Check data fetching**
- Identify request waterfalls — sequential API calls that could be parallelized with `Promise.all`.
- Look for data fetched on the client that could be fetched on the server.
- Check for missing pagination on large data sets.
- Verify API responses aren't over-fetching (returning fields the client doesn't need).
4. **Database query optimization**
- Look for N+1 query patterns (a query per item in a list).
- Check for missing indexes on columns used in WHERE, ORDER BY, and JOIN clauses.
- Identify queries that could use `SELECT` with specific columns instead of `SELECT *`.
- Look for missing connection pooling.
5. **Check assets**
- Verify images use modern formats (WebP/AVIF) and are properly sized.
- Check for missing `loading="lazy"` on below-the-fold images.
- Verify fonts use `font-display: swap` and are preloaded.
- Check for render-blocking CSS or JavaScript.
6. **Generate recommendations** — produce a prioritized list of optimizations ranked by impact (High / Medium / Low) with estimated effort for each.
## Notes
- Focus on measurable improvements — use Lighthouse, WebPageTest, or the Performance tab in DevTools.
- Don't prematurely optimize — profile first, optimize bottlenecks.
- For React apps, use React DevTools Profiler to identify slow components.

View File

@ -1,51 +0,0 @@
---
name: auditing-security
description: Perform a systematic security audit of a codebase, checking for OWASP Top 10 vulnerabilities, secrets exposure, and insecure patterns.
---
# Security Audit
Use this skill when the user asks to audit security, check for vulnerabilities, review code for security issues, or harden an application.
## Steps
1. **Scan for hardcoded secrets** — search for API keys, tokens, passwords, and connection strings in source files. Check for patterns like:
- `password=`, `secret=`, `token=`, `api_key=`
- Base64-encoded credentials
- AWS keys (`AKIA...`), Stripe keys (`sk_live_...`), GitHub tokens (`ghp_...`)
- Files: `.env` committed to git, `config.json` with credentials
2. **Check authentication & authorization**
- Verify all API routes check authentication before processing.
- Ensure role-based access control is enforced server-side, not just in the UI.
- Check that password hashing uses bcrypt/argon2 (not MD5/SHA1).
- Verify session tokens are HTTP-only, secure, and have reasonable expiry.
3. **Check for injection vulnerabilities**
- **SQL injection**: look for string concatenation in SQL queries instead of parameterized queries.
- **XSS**: look for `dangerouslySetInnerHTML`, `innerHTML`, or unescaped user input rendered in templates.
- **Command injection**: look for `exec()`, `eval()`, `child_process.exec()` with user input.
- **Path traversal**: check file operations for unsanitized user input in paths.
4. **Review dependency security**
- Run `npm audit` or `pip audit` to check for known vulnerabilities.
- Flag outdated dependencies with known CVEs.
- Check for overly permissive dependency ranges.
5. **Check CORS and CSP configuration**
- Verify CORS doesn't use `Access-Control-Allow-Origin: *` in production.
- Check for Content Security Policy headers.
- Verify `X-Frame-Options`, `X-Content-Type-Options`, and `Strict-Transport-Security` headers.
6. **Review data exposure**
- Check API responses for leaking sensitive fields (password hashes, internal IDs, PII).
- Verify error messages don't expose stack traces or internal details in production.
- Check logging for sensitive data being written to logs.
7. **Generate report** — produce a summary with severity ratings (Critical / High / Medium / Low) for each finding, with the file path, line number, and recommended fix.
## Notes
- This is a code review, not a penetration test. Recommend tools like `npm audit`, `trivy`, or `snyk` for automated scanning.
- Always check `.gitignore` to ensure `.env`, credentials, and key files are excluded.
- For comprehensive auditing, recommend the OWASP Testing Guide.

View File

@ -1,66 +0,0 @@
---
name: auto-type-checking
description: Run TypeScript type checking after file edits and immediately flag type errors before moving on. Uses Cursor hooks for automatic enforcement.
user-invocable: true
---
# Auto Type Checking
Catch type errors immediately after every edit instead of discovering them at build time.
## Manual Workflow
After editing a TypeScript file, run:
```bash
npx tsc --noEmit 2>&1 | head -30
```
If errors appear, fix them before moving on.
## Automated with Cursor Hooks
Add to `.cursor/hooks.json` to run automatically after every file edit:
```json
{
"hooks": [
{
"event": "afterFileEdit",
"script": "check-types.sh",
"pattern": "**/*.{ts,tsx}"
}
]
}
```
Create `.cursor/hooks/check-types.sh`:
```bash
#!/bin/bash
# Quick type check — only reports errors, doesn't block
npx tsc --noEmit --pretty 2>&1 | head -20
exit 0 # Don't block the agent even if there are errors
```
```bash
chmod +x .cursor/hooks/check-types.sh
```
## What to Check
When type errors appear:
1. **Missing imports**: `Cannot find name 'X'` → add the import
2. **Type mismatches**: `Type 'string' is not assignable to type 'number'` → fix the type or the value
3. **Missing properties**: `Property 'x' does not exist on type 'Y'` → add the property to the interface or fix the access
4. **Null safety**: `Object is possibly 'null'` → add null check or optional chaining
5. **Generic constraints**: `Type 'X' does not satisfy the constraint 'Y'` → fix the generic parameter
## Tips
- Use `--noEmit` to type-check without producing output files
- For large projects, `tsc` can be slow — consider `--incremental` or running only on changed files
- If using path aliases, ensure `tsconfig.json` paths are configured correctly
- For monorepos, run `tsc` from the package root, not the workspace root
- Pair with `grinding-until-pass` for a full "fix until clean" loop

View File

@ -1,114 +0,0 @@
---
name: babysitting-pr
description: Monitor a pull request for CI failures, review comments, and merge conflicts — then fix them automatically. Use when a PR is open and you want the agent to keep it merge-ready.
---
# Babysitting a PR
Use this skill when the user has an open pull request and wants the agent to monitor it, fix CI failures, resolve review comments, and keep it merge-ready.
## Steps
1. **Get the PR status** — fetch the current state of the PR:
```bash
gh pr view --json number,title,state,mergeable,reviewDecision,statusCheckRollup,comments,reviews
```
Also check for merge conflicts:
```bash
gh pr view --json mergeStateStatus
```
2. **Check CI status** — look at the `statusCheckRollup` field. For each failing check:
```bash
gh pr checks
```
This lists all CI checks and their status (pass/fail/pending).
3. **Fix CI failures** — for each failing check, get the logs:
```bash
gh run view <run-id> --log-failed
```
Analyze the failure and fix it:
- **Lint failures**: run the linter locally (`npm run lint -- --fix`), fix remaining issues manually, commit.
- **Type errors**: run `npx tsc --noEmit`, read the errors, fix the types, commit.
- **Test failures**: run the failing test suite locally, read the assertion errors, fix the code or update the test expectations, commit.
- **Build failures**: run `npm run build`, read the error output, fix imports/configs/missing deps, commit.
After fixing, push the changes:
```bash
git add -A && git commit -m "fix: resolve CI failures" && git push
```
4. **Handle review comments** — fetch PR review comments:
```bash
gh api repos/{owner}/{repo}/pulls/{pr}/comments
```
For each unresolved comment:
- Read the comment and the code it references.
- If the fix is clear (typo, naming, missing null check, style issue), apply it.
- If the comment requires a design decision or clarification, skip it and report to the user.
Commit fixes for resolved comments:
```bash
git add -A && git commit -m "fix: address review feedback" && git push
```
5. **Resolve merge conflicts** — if the PR has conflicts:
```bash
git fetch origin main
git merge origin/main
```
Resolve conflicts by reading both sides and choosing the correct resolution. For ambiguous conflicts, ask the user. After resolving:
```bash
git add -A && git commit -m "fix: resolve merge conflicts" && git push
```
6. **Re-check status** — after pushing fixes, wait for CI to run and check again:
```bash
gh pr checks --watch
```
If new failures appear, go back to step 3. Limit to 3 rounds to avoid infinite loops.
7. **Report** — summarize what was done:
- Which CI checks were failing and how they were fixed
- Which review comments were addressed
- Whether merge conflicts were resolved
- Current PR status (ready to merge, or what's still blocking)
## Loop Behavior
This skill is designed to run in a loop:
```
Check PR → Find issues → Fix issues → Push → Re-check → Repeat
```
Stop when:
- All checks pass, no unresolved comments, no conflicts → PR is merge-ready
- 3 fix-push-check cycles have been attempted without full resolution → report what's still failing
- A fix requires a design decision → ask the user
## Notes
- Never force-push to a shared PR branch.
- Don't modify test assertions to make tests pass unless the behavior change was intentional.
- Don't resolve review comments you're unsure about — skip them and let the user know.
- If CI is queued/pending, wait for it to complete before analyzing failures.
- Use `gh pr ready` to mark the PR as ready for review once everything is green.

View File

@ -1,52 +0,0 @@
---
name: best-of-n-solving
description: Solve a hard problem by trying multiple approaches in parallel using isolated git worktrees. Each attempt runs in its own branch, and the best solution is selected. Use for complex refactors, tricky bugs, or architectural decisions where multiple strategies could work.
---
# Best-of-N Problem Solving
Use this skill when facing a hard problem with multiple possible approaches — complex refactors, tricky bugs, performance optimization, or architectural decisions where you're not sure which strategy will work best.
## How It Works
Cursor's `best-of-n-runner` subagent type creates isolated git worktrees — each attempt gets its own branch and working directory. Multiple approaches run in parallel without interfering with each other. You compare the results and pick the winner.
## Steps
1. **Identify the approaches** — before launching, define 2-3 distinct strategies. For example, if optimizing a slow database query:
- Approach A: Add a composite index and rewrite the query
- Approach B: Denormalize the schema with a materialized view
- Approach C: Add application-level caching with Redis
2. **Launch parallel runners** — use the Task tool with `subagent_type: "best-of-n-runner"` for each approach. Launch them all in a single message so they run concurrently:
```
Task 1: { subagent_type: "best-of-n-runner", prompt: "Approach A: ..." }
Task 2: { subagent_type: "best-of-n-runner", prompt: "Approach B: ..." }
Task 3: { subagent_type: "best-of-n-runner", prompt: "Approach C: ..." }
```
Each runner gets its own branch and worktree. Include clear success criteria in the prompt (e.g., "run the tests and report if they pass", "measure the query time").
3. **Compare results** — when all runners complete, evaluate:
- Which approach passes all tests?
- Which has the cleanest implementation?
- Which has the best performance characteristics?
- Which is easiest to maintain long-term?
4. **Merge the winner** — check out the winning branch and merge it, or cherry-pick specific commits. Clean up the other worktree branches.
## When to Use This
- A bug that could have multiple root causes
- A refactor where you're choosing between patterns (e.g., composition vs. inheritance)
- Performance optimization with multiple strategies
- Trying different libraries or approaches for the same feature
- Any situation where "just try it" is faster than analyzing
## Notes
- Each runner is fully isolated — they can't see each other's changes.
- Keep prompts specific: include the file paths, the problem statement, and clear success criteria.
- For simpler problems, this is overkill — just use a single agent.
- The branches are real git branches, so you can inspect them manually if needed.

View File

@ -1,69 +0,0 @@
---
name: building-skills-from-patterns
description: When the same multi-step workflow repeats in Cursor (user corrections or agent redos), capture it as a new SKILL.md under .cursor/skills/ so future sessions load it automatically.
user-invocable: true
---
# Building Skills From Patterns
**Skills** are reusable `SKILL.md` files. This meta-skill tells the agent to **promote repeated muscle memory** into a named skill: research once, encode the workflow, reuse forever.
## When to trigger
- The user has asked for the **same sequence** three or more times (e.g. “always run lint then tsc then test before commit”).
- The agent notices it is **re-deriving** the same steps on every task in this repo (e.g. “how we deploy preview branches”).
- A correction sounds like a **policy** (“never use raw SQL here — always the repository layer”) — pair with `suggesting-cursor-rules` if it should be always-on; use a **skill** if it is a procedure with steps.
## Workflow
### 1. Name the pattern
Choose a short **slug** (lowercase, hyphens): `verifying-api-before-merge`, `releasing-mobile-build`, etc.
### 2. Draft `SKILL.md`
Create `.cursor/skills/<slug>/SKILL.md` (or in this repos pattern, copy from `resources/<slug>/SKILL.md` when contributing upstream).
Frontmatter:
```yaml
---
name: <slug>
description: One line: what it does and when to use it. Ends with a clear trigger.
user-invocable: true # optional, if the user should be able to invoke by name
---
```
Body sections (keep lean):
1. **Title** — human-readable.
2. **When to use** — bullets.
3. **Steps** — numbered, imperative, tool names where useful (`npm`, `gh`, MCP tools).
4. **Notes** — edge cases, safety, when **not** to use.
Match the tone of other skills in the repo: concrete commands, no filler.
### 3. Validate
- **Description** is specific enough for Cursor to **match** the skill when the user describes the task.
- Steps are **executable** by an agent without guessing repo layout (or say “detect package manager from lockfile”).
- No secrets or machine-specific paths.
### 4. Point the user to it
Tell the user where the file lives and that the agent will pick it up on the next chat in that workspace.
## Relationship to rules and hooks
| Mechanism | Use for |
|----------|---------|
| **Skill** | On-demand procedure, branching steps, tool usage. |
| **Rule** (`.cursor/rules/`) | Always-on conventions, style, file patterns. |
| **Hook** (`.cursor/hooks.json`) | Automate after file save / stop events. |
If the pattern is “every time I save, run X,” suggest a **hook** instead. If it is “when I ask to ship,” keep it as a **skill**.
## Notes
- Prefer **one skill per workflow** — avoid megaskills that try to cover every situation.
- Update an existing skill instead of adding a duplicate if the workflow evolves.

View File

@ -1,74 +0,0 @@
---
name: codebase-onboarding
description: Launch multiple explore subagents in parallel to investigate architecture, data models, auth, APIs, and deployment. Synthesize into an onboarding document.
user-invocable: true
---
# Codebase Onboarding
Generate a comprehensive onboarding document for a codebase by exploring it in parallel.
## Workflow
### 1. Launch Parallel Explorers
Spawn 5 `explore` subagents, each investigating a different area:
**Agent 1 — Architecture & Structure**
> "Map the top-level directory structure. Identify the framework (Next.js, Express, Django, etc.), monorepo tools (turbo, nx), and key config files. List every app/package and what it does."
**Agent 2 — Data Models & Database**
> "Find all database schemas, ORM models, migrations, and seed files. List every entity, its fields, and relationships. Identify the database (Postgres, MySQL, MongoDB, etc.) and ORM (Prisma, Drizzle, SQLAlchemy, etc.)."
**Agent 3 — API Routes & Endpoints**
> "Find all API route definitions. List every endpoint with its HTTP method, path, auth requirements, and what it does. Identify the API style (REST, GraphQL, tRPC)."
**Agent 4 — Authentication & Authorization**
> "Find how auth works. Identify the auth provider (Auth.js, Clerk, Supabase Auth, custom), session management, protected routes, role/permission checks, and middleware."
**Agent 5 — Deployment & Infrastructure**
> "Find deployment config (Dockerfile, Vercel config, fly.toml, terraform), CI/CD pipelines (GitHub Actions, etc.), environment variables needed, and how to run the app locally."
### 2. Synthesize
Combine the results from all 5 agents into a single onboarding document:
```markdown
# Codebase Onboarding
## Quick Start
1. Clone the repo
2. Install dependencies: `<command>`
3. Set up environment: copy `.env.example` to `.env`
4. Run database migrations: `<command>`
5. Start dev server: `<command>`
## Architecture
<Agent 1 findings>
## Data Models
<Agent 2 findings>
## API Reference
<Agent 3 findings>
## Authentication
<Agent 4 findings>
## Deployment
<Agent 5 findings>
## Key Files to Know
- `<file>`<why it matters>
```
### 3. Save
Write the document to `ONBOARDING.md` in the project root, or wherever the user specifies.
## Tips
- Each explore agent is read-only and fast — the whole process takes under a minute
- For monorepos, consider one additional agent per app/package
- The document should be opinionated — highlight the "start here" files, not just list everything
- Include gotchas: common setup issues, env vars that are easy to forget, required system dependencies

View File

@ -1,85 +0,0 @@
---
name: comparing-branches-visually
description: Check out two branches in separate worktrees, start both dev servers on different ports, screenshot the same pages, and produce a visual diff.
user-invocable: true
---
# Comparing Branches Visually
Create a visual before/after comparison of UI changes between two branches.
## Workflow
### 1. Set Up Two Worktrees
Use `best-of-n-runner` subagents or git worktrees to run both branches simultaneously:
```bash
# Create a worktree for the base branch
git worktree add /tmp/branch-compare-base main
# The current working directory has the feature branch
```
### 2. Start Both Servers
Start the base branch server on a different port:
```bash
# In the base worktree
cd /tmp/branch-compare-base && PORT=3001 npm run dev
# Current branch is already on the default port (3000)
```
### 3. Identify Pages to Compare
Determine which pages are affected by the changes:
```bash
git diff main --name-only | grep -E '\.(tsx?|jsx?|vue|svelte|css)'
```
Map changed files to their routes (e.g. `app/dashboard/page.tsx``/dashboard`).
### 4. Screenshot Both Versions
For each affected page:
1. `browser_navigate` to `http://localhost:3001/<page>` (base branch)
2. `browser_take_screenshot` → save as "before"
3. `browser_navigate` to `http://localhost:3000/<page>` (feature branch)
4. `browser_take_screenshot` → save as "after"
### 5. Report
Present the comparison:
```
Visual Diff: feature/redesign-header vs main
/dashboard:
Before: [screenshot from main]
After: [screenshot from feature branch]
Changes: Header height reduced, nav links repositioned, new avatar dropdown
/settings:
Before: [screenshot]
After: [screenshot]
Changes: No visual differences detected
```
### 6. Clean Up
```bash
# Stop the base branch server
# Remove the worktree
git worktree remove /tmp/branch-compare-base
```
## Tips
- Test at a consistent viewport size (1280×800 is a good default)
- For mobile-first changes, also compare at 375px width
- If the app requires auth, log in on both ports first
- This pairs well with `screenshotting-changelog` for PR descriptions

View File

@ -1,100 +0,0 @@
---
name: converting-css-modules-to-tailwind
description: Migrate CSS Modules (.module.css/.module.scss) to Tailwind utility classes. Handles styles object removal, className interpolation, composition, and global overrides.
user-invocable: true
---
# Converting CSS Modules to Tailwind
Migrate a component from CSS Modules (`.module.css` / `.module.scss`) to Tailwind utility classes.
## Workflow
### 1. Inventory the Module
Read the `.module.css` file and the component that imports it. Map every `styles.xxx` reference to the CSS rule it resolves to.
```tsx
// Before
import styles from './Card.module.css';
<div className={styles.card}>
<h2 className={styles.title}>{title}</h2>
<p className={styles.body}>{children}</p>
</div>
```
```css
/* Card.module.css */
.card { display: flex; flex-direction: column; gap: 16px; padding: 24px; border-radius: 12px; background: white; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
.title { font-size: 20px; font-weight: 600; color: #111827; }
.body { font-size: 14px; color: #6b7280; line-height: 1.6; }
```
### 2. Convert Each Class
Replace `styles.xxx` with equivalent Tailwind utilities:
```tsx
// After
<div className="flex flex-col gap-4 p-6 rounded-xl bg-white shadow-sm">
<h2 className="text-xl font-semibold text-gray-900">{title}</h2>
<p className="text-sm text-gray-500 leading-relaxed">{children}</p>
</div>
```
### 3. Handle CSS Modules Patterns
**`composes` keyword:**
```css
.base { padding: 8px 16px; border-radius: 4px; }
.primary { composes: base; background: blue; color: white; }
```
→ Flatten into a single set of utilities. If reuse is needed, extract a component, not a class.
**Conditional classNames with `clsx`/`classnames`:**
```tsx
// Before
className={clsx(styles.button, isActive && styles.active)}
// After
className={clsx("px-4 py-2 rounded", isActive && "bg-blue-600 text-white")}
```
**Dynamic class selection:**
```tsx
// Before
className={styles[variant]}
// After — use a lookup object
const variantClasses = {
primary: "bg-blue-600 text-white hover:bg-blue-700",
secondary: "bg-gray-100 text-gray-900 hover:bg-gray-200",
danger: "bg-red-600 text-white hover:bg-red-700",
};
className={variantClasses[variant]}
```
**CSS Modules global overrides:**
```css
:global(.some-library-class) { ... }
```
→ Move to `globals.css` with `@layer components { }` or use Tailwind's `@apply` in the global stylesheet.
**SCSS features (nesting, variables, mixins):**
- Nested selectors → flatten into utility classes on each element
- SCSS `$variables` → map to `tailwind.config.ts` theme values
- Mixins → replace with utility composition or extract components
### 4. Clean Up
1. Remove the `import styles from './Xxx.module.css'` line
2. Delete the `.module.css` / `.module.scss` file
3. If the component had a co-located `index.ts` barrel that re-exported styles, update it
4. Search the codebase for any other imports of the deleted module
5. Run the app and verify visually — check for regressions
## Rules
- Convert one component at a time — don't batch entire directories
- Keep conditional logic in `clsx()` or template literals, not in CSS
- If a module has pseudo-element styles (`:before`, `:after` with `content`), those need `before:` / `after:` prefixes plus `content-['...']` in Tailwind
- For `:nth-child`, `:first-of-type`, etc. — check if Tailwind has a matching variant, otherwise keep a minimal CSS rule
- Don't create `@apply` classes to replicate what the module did — the goal is to eliminate the indirection

View File

@ -1,113 +0,0 @@
---
name: converting-css-to-tailwind
description: Convert plain CSS stylesheets to Tailwind CSS utility classes. Handles selectors, media queries, pseudo-classes, custom properties, and animations.
user-invocable: true
---
# Converting CSS to Tailwind
Migrate plain CSS files to Tailwind utility classes applied directly in markup.
## Workflow
1. **Read the CSS file** and inventory every rule
2. **Find the corresponding markup** (HTML, JSX, TSX, Vue, Svelte) that references each selector
3. **Convert each rule** using the mapping below
4. **Delete the CSS rule** once all its properties are expressed as utilities
5. **Remove the CSS file** (or import) once it's empty
6. **Verify** the page looks identical — check for visual regressions
## Conversion Reference
### Layout & Box Model
| CSS | Tailwind |
|-----|----------|
| `display: flex` | `flex` |
| `display: grid` | `grid` |
| `display: none` | `hidden` |
| `position: relative` | `relative` |
| `position: absolute` | `absolute` |
| `justify-content: center` | `justify-center` |
| `align-items: center` | `items-center` |
| `gap: 16px` | `gap-4` |
| `width: 100%` | `w-full` |
| `max-width: 768px` | `max-w-3xl` |
| `margin: 0 auto` | `mx-auto` |
| `padding: 16px` | `p-4` |
| `overflow: hidden` | `overflow-hidden` |
### Typography
| CSS | Tailwind |
|-----|----------|
| `font-size: 14px` | `text-sm` |
| `font-weight: 700` | `font-bold` |
| `line-height: 1.5` | `leading-normal` |
| `text-align: center` | `text-center` |
| `text-transform: uppercase` | `uppercase` |
| `color: #333` | `text-[#333]` or a theme color |
| `letter-spacing: 0.05em` | `tracking-wide` |
### Backgrounds & Borders
| CSS | Tailwind |
|-----|----------|
| `background-color: #f5f5f5` | `bg-[#f5f5f5]` or `bg-neutral-100` |
| `border: 1px solid #e5e7eb` | `border border-gray-200` |
| `border-radius: 8px` | `rounded-lg` |
| `box-shadow: 0 1px 3px ...` | `shadow-sm` |
### Responsive — Media Queries
```css
@media (min-width: 768px) { .card { flex-direction: row; } }
```
`<div class="flex-col md:flex-row">`
Map breakpoints: `sm:` (640), `md:` (768), `lg:` (1024), `xl:` (1280), `2xl:` (1536)
### Pseudo-classes & States
```css
.btn:hover { background-color: #1d4ed8; }
```
`<button class="hover:bg-blue-700">`
Prefixes: `hover:`, `focus:`, `active:`, `disabled:`, `first:`, `last:`, `odd:`, `even:`, `group-hover:`, `peer-checked:`
### Animations & Transitions
```css
transition: all 0.2s ease-in-out;
```
`transition-all duration-200 ease-in-out`
```css
@keyframes spin { ... }
animation: spin 1s linear infinite;
```
`animate-spin` (built-in) or define in `tailwind.config`
### Custom Properties / Arbitrary Values
For anything without a direct utility, use arbitrary values:
- `w-[calc(100%-2rem)]`
- `grid-cols-[200px_1fr_1fr]`
- `text-[clamp(1rem,2vw,1.5rem)]`
## Handling Remaining CSS
Some things can't be expressed purely as utilities:
- **Complex selectors** (`.parent > .child + .sibling`) — restructure the markup or use `@apply` as a last resort
- **`@font-face`** — keep in a global CSS file or `globals.css`
- **Complex `@keyframes`** — define in `tailwind.config.ts` under `theme.extend.keyframes`
- **CSS variables** — migrate to Tailwind theme values in `tailwind.config.ts`
## Rules
- Prefer semantic Tailwind classes (`bg-primary`) over arbitrary hex values when a theme exists
- Don't use `@apply` to recreate the same CSS you're migrating away from — that defeats the purpose
- Group related utilities logically: layout → spacing → typography → colors → effects
- If a component has 10+ utilities, consider extracting a reusable component rather than a CSS class

View File

@ -1,111 +0,0 @@
---
name: creating-pr
description: Create a clean, review-ready pull request with a good title, structured description, linked issues, and appropriate reviewers.
user-invocable: true
---
# Creating a PR
Package work into a pull request that's easy to review and merge.
## Workflow
### 1. Prepare the Branch
Before creating the PR:
```bash
# Ensure branch is up to date with base
git fetch origin
git rebase origin/main # or merge, depending on project convention
# Check what will be in the PR
git log origin/main..HEAD --oneline
git diff origin/main --stat
```
Squash fixup commits if the project prefers clean history. Keep logical commits separate if the project prefers granular history.
### 2. Write the Title
Format: `<type>: <short description>`
| Type | When |
|------|------|
| `feat` | New feature |
| `fix` | Bug fix |
| `refactor` | Code change that neither fixes a bug nor adds a feature |
| `docs` | Documentation only |
| `test` | Adding or fixing tests |
| `chore` | Build, CI, deps, or tooling |
| `perf` | Performance improvement |
Examples:
- `feat: add dark mode toggle to settings page`
- `fix: prevent duplicate form submissions on checkout`
- `refactor: extract auth middleware into shared module`
### 3. Write the Description
Use this structure:
```markdown
## Summary
1-3 sentences explaining what this PR does and why.
Closes #123
## Changes
- Added `ThemeToggle` component with system/light/dark options
- Updated `Layout` to read theme from context
- Added theme persistence to localStorage
## Test Plan
- [ ] Toggle between light/dark/system themes
- [ ] Refresh page — theme persists
- [ ] Check no flash of unstyled content on load
```
### 4. Self-Review
Before requesting review:
- Read every line of the diff yourself
- Remove debug code (`console.log`, `TODO`, commented-out code)
- Verify tests pass: `npm test`
- Verify types: `npx tsc --noEmit`
- Verify lint: `npm run lint`
- Check for files that shouldn't be committed (`.env`, lockfile conflicts)
### 5. Create the PR
```bash
git push -u origin HEAD
gh pr create --title "<title>" --body "$(cat <<'EOF'
## Summary
...
## Changes
...
## Test Plan
...
EOF
)"
```
### 6. Request Review
- Tag the appropriate reviewers (code owners, domain experts)
- If the PR is large (>400 lines), add a comment explaining the best order to review files
- If the PR depends on another PR, note it in the description
- Label the PR appropriately (feature, bug, breaking change, etc.)
## Tips
- Small PRs get reviewed faster — aim for <300 lines changed
- If a PR is too big, split it into stacked PRs
- Screenshots/recordings for UI changes make review much faster
- Draft PRs are useful for early feedback before the work is complete

View File

@ -1,64 +0,0 @@
---
name: dark-mode-testing
description: Toggle between light and dark mode in Cursor's browser, screenshot both states, and flag missing token mappings or contrast issues.
user-invocable: true
---
# Dark Mode Testing
Verify that dark mode works correctly by toggling themes and comparing.
## Workflow
### 1. Open the App
Navigate to the target page using `browser_navigate`.
### 2. Screenshot Light Mode
Take a screenshot of the page in its default (light) state using `browser_take_screenshot`.
### 3. Toggle Dark Mode
Toggle dark mode using one of these methods (try in order):
1. **Class toggle**: Execute JS to add `dark` class to `<html>`:
```javascript
document.documentElement.classList.toggle('dark')
```
2. **Attribute toggle**: Set `data-theme="dark"`:
```javascript
document.documentElement.setAttribute('data-theme', 'dark')
```
3. **Media query**: Use browser to emulate `prefers-color-scheme: dark`
4. **UI toggle**: Find the theme toggle button in `browser_snapshot` and click it
### 4. Screenshot Dark Mode
Take another screenshot after toggling.
### 5. Inspect for Issues
Check the `browser_snapshot` aria tree and screenshots for:
- **White flashes**: Elements with hardcoded `bg-white` instead of `bg-white dark:bg-slate-900`
- **Invisible text**: Text color that matches the dark background (e.g. black text on dark bg)
- **Missing borders**: Borders using light-only colors that disappear on dark backgrounds
- **Contrast violations**: Text that's too low-contrast against the dark background (need 4.5:1)
- **Hardcoded colors**: Any `#ffffff`, `#000000`, `white`, `black` in inline styles
- **Images**: Logos or icons that don't have dark mode variants
- **Shadows**: Box shadows that are invisible on dark backgrounds
- **Form inputs**: Input fields that keep white backgrounds in dark mode
### 6. Report
```
Dark Mode Test:
Light mode: OK
Dark mode issues found:
- Header logo: white logo invisible on dark bg (needs dark variant)
- Card borders: border-gray-200 invisible on dark bg → add dark:border-gray-700
- Footer text: hardcoded #333 → use text-gray-900 dark:text-gray-100
```
Fix each issue and re-test.

View File

@ -1,134 +0,0 @@
---
name: database-design
description: Design database schemas — tables, relationships, indexes, constraints, and ORM setup. Covers relational design, normalization, and common patterns.
user-invocable: true
---
# Database Design
Design a database schema from requirements.
## Workflow
### 1. Identify Entities
From the requirements, extract the core entities (nouns):
- Users, Teams, Projects, Tasks, Comments, etc.
- Each entity becomes a table
### 2. Define Relationships
| Relationship | Implementation |
|-------------|----------------|
| One-to-one | Foreign key with unique constraint, or embed in same table |
| One-to-many | Foreign key on the "many" side |
| Many-to-many | Junction/join table |
| Self-referential | Foreign key pointing to same table (e.g. `parent_id`) |
### 3. Design the Schema
For each table:
```sql
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
avatar_url TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE projects (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name TEXT NOT NULL,
owner_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
```
### 4. Apply Best Practices
**Primary keys:**
- Use `UUID` for distributed systems or public-facing IDs
- Use `SERIAL`/`BIGSERIAL` for internal-only IDs (faster joins)
**Timestamps:**
- Always add `created_at` and `updated_at`
- Use `TIMESTAMPTZ` (with timezone), never `TIMESTAMP`
**Naming:**
- Tables: plural snake_case (`users`, `project_members`)
- Columns: singular snake_case (`user_id`, `created_at`)
- Indexes: `idx_<table>_<columns>` (`idx_users_email`)
**Constraints:**
- `NOT NULL` on everything unless it's genuinely optional
- `UNIQUE` on natural keys (email, slug, external IDs)
- `REFERENCES` with `ON DELETE` behavior (CASCADE, SET NULL, RESTRICT)
- `CHECK` constraints for enums or value ranges
### 5. Add Indexes
```sql
-- For columns you filter/sort by frequently
CREATE INDEX idx_projects_owner_id ON projects(owner_id);
-- For unique lookups
CREATE UNIQUE INDEX idx_users_email ON users(email);
-- Composite for common query patterns
CREATE INDEX idx_tasks_project_status ON tasks(project_id, status);
```
**When to index:**
- Foreign keys (almost always)
- Columns in WHERE clauses
- Columns in ORDER BY
- Columns in JOIN conditions
**When NOT to index:**
- Small tables (<1000 rows)
- Columns with low cardinality (boolean, status with 3 values)
- Columns that are rarely queried
### 6. ORM Setup
**Prisma:**
```prisma
model User {
id String @id @default(uuid())
email String @unique
name String
projects Project[]
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("users")
}
```
**Drizzle:**
```typescript
export const users = pgTable('users', {
id: uuid('id').primaryKey().defaultRandom(),
email: text('email').notNull().unique(),
name: text('name').notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
});
```
## Common Patterns
**Soft deletes:** Add `deleted_at TIMESTAMPTZ` instead of actually deleting rows
**Audit log:** Separate `audit_events` table with `entity_type`, `entity_id`, `action`, `actor_id`, `payload`
**Tags/labels:** Junction table (`task_tags`) with `task_id` + `tag_id`
**Tree/hierarchy:** `parent_id` self-reference, or materialized path (`/1/4/7/`)
**Polymorphic associations:** Use `entity_type` + `entity_id` columns (avoid if possible, prefer separate FKs)
## Tips
- Start normalized (3NF), denormalize only when you have measured performance problems
- Don't store derived data unless you have a caching/invalidation strategy
- Use database enums or check constraints for status fields, not free-text
- Always think about what happens when you delete a parent record

View File

@ -1,75 +0,0 @@
---
name: detecting-port-conflicts
description: Detect EADDRINUSE and port conflicts, find what's using the port, and resolve it by killing the process or suggesting an alternative port.
user-invocable: true
---
# Detecting Port Conflicts
When a dev server fails to start because a port is already in use, diagnose and resolve it.
## Detection
Scan terminal output for these patterns:
- `EADDRINUSE`
- `address already in use`
- `Port XXXX is already in use`
- `bind: address already in use`
- `OSError: [Errno 98] Address already in use`
Extract the port number from the error message.
## Diagnosis
Find what's using the port:
```bash
lsof -i :<PORT> -P -n
```
This shows the PID, process name, and user. Common culprits:
- A previous dev server that didn't shut down cleanly
- Another project's dev server
- A Docker container
- A system service
## Resolution Options
### Option 1: Kill the blocking process
```bash
kill <PID>
# If it doesn't stop:
kill -9 <PID>
```
Then restart the original server.
### Option 2: Use a different port
Suggest the next available port:
```bash
# Check if port+1 is free
lsof -i :<PORT+1> -P -n
```
Update the dev server config or start command:
- Next.js: `next dev -p <PORT>`
- Vite: `vite --port <PORT>`
- Express: set `PORT` env var
- Django: `python manage.py runserver <PORT>`
### Option 3: Kill all node processes (nuclear option)
```bash
killall node
```
Only suggest this if the user confirms — it kills everything.
## Tips
- On macOS, ports below 1024 require root
- Docker containers bind ports that persist even if the container is stopped — check `docker ps`
- If `lsof` shows nothing, the port may be in TIME_WAIT state — just wait 30 seconds or use a different port

View File

@ -1,100 +0,0 @@
---
name: exporting-to-png
description: Export code, terminal output, diagrams, or UI components to PNG images using headless browser rendering or CLI tools.
user-invocable: true
---
# Exporting to PNG
Convert code snippets, Markdown content, terminal output, diagrams, or rendered UI components into PNG image files.
## Methods
### 1. HTML → PNG via Headless Browser
The most flexible approach. Render any content as HTML and screenshot it.
```bash
# Using Playwright (if available)
npx playwright screenshot --full-page "file:///path/to/content.html" output.png
# Using Puppeteer one-liner
node -e "
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(\`<html>...</html>\`);
await page.screenshot({ path: 'output.png', fullPage: true });
await browser.close();
})();
"
```
**Steps:**
1. Generate an HTML file with the content styled appropriately (syntax highlighting, padding, fonts)
2. Use a headless browser to render and capture
3. Crop if needed using an image tool
### 2. Code → PNG with Carbon or Silicon
For styled code screenshots:
```bash
# silicon (Rust CLI, fast)
silicon --language python --output code.png source.py
silicon --from-clipboard --output code.png
# Or generate a Carbon URL for browser capture
# https://carbon.now.sh/?l=python&code=<url-encoded-code>
```
### 3. Mermaid Diagrams → PNG
```bash
# Using mermaid-cli
npx @mermaid-js/mermaid-cli mmdc -i diagram.mmd -o diagram.png -b transparent
# Or with Docker
docker run --rm -v "$(pwd)":/data minlag/mermaid-cli mmdc -i /data/diagram.mmd -o /data/diagram.png
```
### 4. SVG → PNG
```bash
# Using sharp (Node.js)
node -e "
const sharp = require('sharp');
sharp('input.svg').png().toFile('output.png');
"
# Using Inkscape CLI
inkscape input.svg --export-type=png --export-filename=output.png
# Using ImageMagick
convert input.svg output.png
```
### 5. Terminal Output → PNG
```bash
# Using termshot (if installed)
termshot -- ls -la
# Manual approach: capture output, wrap in HTML with monospace font, screenshot
```
## Workflow
1. Determine the content type (code, diagram, HTML, terminal, SVG)
2. Check which tools are available in the environment (`which silicon`, `npx --help`, etc.)
3. Choose the best method and generate the PNG
4. Verify the output exists and is non-empty: `file output.png && ls -la output.png`
5. Report the file path and dimensions
## Tips
- For code screenshots, use a dark theme with generous padding (32px+) for a polished look
- Set `deviceScaleFactor: 2` in Playwright/Puppeteer for retina-quality output
- For transparent backgrounds, use `--background transparent` or `omitBackground: true`
- If no specialized tool is installed, fall back to the HTML + headless browser method — it works for everything

View File

@ -1,100 +0,0 @@
---
name: finding-dev-server-url
description: Scan running terminals for dev server URLs (localhost ports), report them, and optionally open the app in Cursor's built-in browser.
user-invocable: true
---
# Finding Dev Server URL
Detect which dev servers are running, what ports they're on, and open them.
## How It Works
Cursor stores live terminal output in text files. Each terminal has a file at:
```
<terminals_folder>/<id>.txt
```
The terminals folder path is provided in your system context. Each file contains metadata (pid, cwd, last command) followed by the full terminal output.
## Workflow
### 1. List All Terminals
```bash
ls <terminals_folder>/*.txt
```
### 2. Read Each Terminal's Metadata
Read the first ~10 lines of each terminal file to see:
- `pid` — process ID
- `cwd` — working directory
- `last_command` — what's running (e.g. `npm run dev`, `pnpm dev`, `python manage.py runserver`)
Skip terminals where the last command is clearly not a server (e.g. `git status`, `ls`, `cd`).
### 3. Scan for Server URLs
Read the full content of terminals that look like they're running a server. Search for these patterns:
| Framework | Pattern |
|-----------|---------|
| Next.js | `Local: http://localhost:XXXX` or `▲ Ready` |
| Vite | `Local: http://localhost:XXXX/` |
| Create React App | `Local: http://localhost:XXXX` |
| Express | `listening on port XXXX` or `listening at http://...` |
| Django | `Starting development server at http://127.0.0.1:XXXX/` |
| Rails | `Listening on http://127.0.0.1:XXXX` |
| Flask | `Running on http://127.0.0.1:XXXX` |
| Go | `Listening on :XXXX` or `http server started on :XXXX` |
| PHP | `Development Server (http://localhost:XXXX) started` |
| Remix | `http://localhost:XXXX` |
| Astro | `http://localhost:XXXX` |
| Nuxt | `http://localhost:XXXX` |
Regex to match most server output:
```
https?://(localhost|127\.0\.0\.1|0\.0\.0\.0)(:\d+)
```
Also check for standalone port patterns:
```
(listening|started|running|ready|serving).*(port\s*|:)\s*(\d{4,5})
```
### 4. Report
Print a summary:
```
Dev servers found:
Terminal 1 (pid 12345) — npm run dev → http://localhost:3000 (cwd: /Users/me/app)
Terminal 3 (pid 67890) — python manage.py runserver → http://127.0.0.1:8000 (cwd: /Users/me/api)
```
If no servers are found, say so and suggest starting one.
### 5. Open in Browser (Optional)
If the user wants to view the app, use Cursor's built-in browser:
```
browser_navigate → http://localhost:<port>
```
Then take a screenshot to confirm it's rendering:
```
browser_take_screenshot
```
## Tips
- If multiple servers are found, ask the user which one to open
- If a terminal shows an error (e.g. `EADDRINUSE`, `address already in use`), report the conflict
- If the server crashed (process exited), note that too — check for `exit_code` in the terminal file footer
- Common default ports: Next.js (3000), Vite (5173), Django (8000), Rails (3000), Flask (5000), Go (8080)

View File

@ -1,66 +0,0 @@
---
name: fixing-broken-links
description: Crawl all links in a file or project, test each for a valid HTTP response, report broken ones, and fix or remove them.
user-invocable: true
---
# Fixing Broken Links
Scan a file (or set of files) for URLs, test every link, and fix any that are broken.
## Workflow
### 1. Extract All Links
Read the target file(s) and collect every URL:
- Markdown links: `[text](url)`
- Bare URLs: `https://...`
- HTML `href` and `src` attributes
- Reference-style link definitions: `[id]: url`
- Local relative paths: `./path/to/file`, `resources/foo/SKILL.md`
### 2. Test Each Link
**For external URLs:**
- Use `curl -sL -o /dev/null -w "%{http_code}" --max-time 10 "<url>"` to get the HTTP status code
- Batch independent checks for speed (run multiple curl commands in parallel or in quick succession)
- Classify results:
- `200``299` → OK
- `301`/`302` → OK but note the redirect target
- `403` → Might be valid (some sites block curl); try with a browser user-agent header
- `404` → Broken
- `429` → Rate limited; retry once after a short pause
- `000` or timeout → Retry once; if still failing, mark as unreachable
**For local file paths:**
- Check if the file exists on disk with `[ -f "path" ]`
- If it's a relative path, resolve it from the file's directory
### 3. Fix Broken Links
For each broken link:
1. Search the web for the correct/current URL (the resource may have moved)
2. If found, replace the old URL with the new one
3. If the resource no longer exists, note it and either:
- Remove the link and leave the text
- Comment it out with a note
- Replace with an archived version (web.archive.org)
### 4. Report
Produce a summary table:
```
| URL | Status | Action |
|-----|--------|--------|
| https://example.com/page | 200 | OK |
| https://old.example.com/moved | 404 → 301 | Updated to https://new.example.com/page |
| ./docs/missing.md | MISSING | Removed link |
```
## Tips
- For large files with many links, batch curl calls to avoid slowdowns
- Some sites (GitHub, npm) rate-limit aggressively — space out requests
- Always re-read the file after making changes to confirm replacements didn't break formatting
- For Markdown files, verify link syntax is preserved: `[text](url)` not `[text]( url )` (no extra spaces)

View File

@ -1,71 +0,0 @@
---
name: form-testing
description: Use Cursor's browser to fill and submit every form in the app with valid and invalid data, verifying validation, error states, and success flows.
user-invocable: true
---
# Form Testing
Systematically test every form in the app using Cursor's built-in browser.
## Workflow
### 1. Find All Forms
Use `browser_snapshot` to get the accessibility tree. Look for `form` elements, or groups of `input`, `select`, `textarea` elements.
Navigate through the app's main pages to discover all forms:
- Login / signup pages
- Settings / profile pages
- Search bars
- Contact / feedback forms
- Checkout flows
- Modals with inputs
### 2. Test Each Form
For each form, run three test passes:
**Pass 1: Empty submission**
- Submit the form with all fields empty
- Verify validation errors appear for required fields
- Check that no server error occurs (should be client-side validation)
**Pass 2: Invalid data**
- Email fields: enter `notanemail`
- Password fields: enter `a` (too short)
- Number fields: enter `abc`
- Phone fields: enter `12345`
- URL fields: enter `not-a-url`
- Check that appropriate error messages appear
**Pass 3: Valid data**
- Fill every field with realistic test data using `browser_fill` or `browser_fill_form`
- Submit the form
- Verify success state (redirect, toast, confirmation message)
- Check `browser_console_messages` for errors
- Check `browser_network_requests` for failed API calls
### 3. Check Edge Cases
- **Double submission**: Click submit twice quickly — should be prevented
- **Long input**: Paste a very long string (1000+ chars) — should be truncated or rejected
- **Special characters**: Enter `<script>alert('xss')</script>` — should be escaped
- **Tab order**: Use `browser_press` with Tab to verify focus moves logically through fields
### 4. Report
```
Form Test Results:
Login form (/login):
Empty submit: PASS — shows "Email required", "Password required"
Invalid email: PASS — shows "Invalid email"
Valid submit: PASS — redirects to /dashboard
XSS check: PASS — input escaped
Settings form (/settings):
Empty submit: FAIL — submits without validation, returns 500
Valid submit: PASS — shows "Settings saved" toast
```
Fix any failures found.

View File

@ -1,10 +0,0 @@
# Copy this file to `.env` and fill in your real key.
# Get a key at https://platform.openai.com/api-keys
#
# Your OpenAI org must be verified for `gpt-image-2`:
# https://platform.openai.com/settings/organization/general
#
# Then load it into your shell before running the script:
# set -a && source .env && set +a
OPENAI_API_KEY=sk-replace-me

View File

@ -1,365 +0,0 @@
---
name: generating-images
description: >-
Generate or edit images using the OpenAI Image API (gpt-image-2). Use when
the user asks to generate, create, draw, render, illustrate, mock up, or edit
an image, icon, logo, mockup, illustration, OG image, blog hero, marketing
asset, or similar visual. Also use when the user supplies a reference image
and asks to modify, restyle, or remix it. Triggers on: "generate an image",
"create an image", "make a picture of", "edit this image", "restyle this",
"make a mockup of", "draw a", "render a", "illustration of".
user-invocable: true
---
# Generating Images (OpenAI gpt-image-2)
Use this skill any time the user asks to generate or edit an image. It wraps
OpenAI's `gpt-image-2` model via a Python script, supports both text-only
prompts and one-or-more reference images, and writes the resulting PNG/JPEG/WebP
to disk.
## Hard rules (do not violate)
1. **Always use `gpt-image-2`.** Never fall back to `gpt-image-1`, `dall-e-3`,
or any other model. The script has no `--model` flag for this reason.
2. **Fail fast on any error.** Do not retry, do not swap models, do not patch
around missing credentials, do not silently degrade quality. If the script
exits non-zero, surface the error to the user verbatim and stop.
3. **Do not "fix" a missing `OPENAI_API_KEY`** by reading from `.env` files,
1Password, etc. unless the user explicitly tells you to. If the env var is
missing, ask the user how they want to provide it (or to `export` it) and
then stop.
## When to use
- User asks for a generated image: icon, logo, illustration, mockup, OG image,
blog hero, marketing asset, concept art, diagram-style image, etc.
- User provides one or more images and asks to edit, restyle, combine, or use
them as references.
- User asks to remove/replace part of an image (use `--mask`).
Do **not** use this skill for:
- Charts/plots/data viz (generate via code instead).
- Sourcing existing photos (use a stock photo skill if available).
- Screenshots of the user's app (use a screenshot skill if available).
## Prerequisites
### 1. OpenAI API key
You need an `OPENAI_API_KEY` exported in your environment. Get one at
[platform.openai.com/api-keys](https://platform.openai.com/api-keys).
The skill ships with a `.env.example` next to this `SKILL.md`. Copy it and
fill in your key:
```bash
cp .env.example .env
# then edit .env and put your real key in
```
Then export it before running the script:
```bash
set -a && source .env && set +a
```
Or just export it directly in your shell:
```bash
export OPENAI_API_KEY="sk-..."
```
If `OPENAI_API_KEY` is not set, the script exits with code 2 immediately.
**Do not** try to read it from anywhere else without the user's explicit
permission.
### 2. Org verification
Your OpenAI org must be verified for `gpt-image-2` at
[platform.openai.com/settings/organization/general](https://platform.openai.com/settings/organization/general).
If you see a 403 mentioning "organization must be verified", surface it and
stop — do not switch models.
### 3. Python dependency
```bash
pip install --upgrade openai
```
## Script location
The Python script lives next to this `SKILL.md` at `scripts/generate_image.py`.
When this skill is installed at `~/.cursor/skills/generating-images/`, the
script will be at `~/.cursor/skills/generating-images/scripts/generate_image.py`.
It prints the absolute path(s) of the written image(s) to stdout. Errors go
to stderr with a non-zero exit code, and the script exits immediately on the
first error.
## How to invoke
Always run via the Shell tool. Pick a sensible output path inside the user's
current workspace (e.g. `./public/generated/<slug>.png` for web projects, or
`./<slug>.png` otherwise).
### 1. Text-to-image
```bash
python3 ~/.cursor/skills/generating-images/scripts/generate_image.py \
--prompt "Minimal flat-vector app icon for a note-taking app, indigo gradient, rounded square, soft shadow" \
--size 1024x1024 \
--quality high \
--out ./icon.png
```
### 2. Image-to-image (one reference)
```bash
python3 ~/.cursor/skills/generating-images/scripts/generate_image.py \
--prompt "Restyle this photo as a watercolor painting with warm tones" \
--image ./photo.jpg \
--out ./photo-watercolor.png
```
### 3. Multiple reference images
```bash
python3 ~/.cursor/skills/generating-images/scripts/generate_image.py \
--prompt "Photorealistic flat-lay product shot combining all of these items on a white background" \
--image ./a.png --image ./b.png --image ./c.png \
--out ./flatlay.png
```
### 4. Masked edit (inpainting)
The mask must be the same size and format as the first input image, with an
alpha channel marking the editable region.
```bash
python3 ~/.cursor/skills/generating-images/scripts/generate_image.py \
--prompt "Replace the sky with a vivid sunset" \
--image ./scene.png --mask ./sky-mask.png \
--out ./scene-sunset.png
```
### 5. Batch / parallel mode (many distinct images at once)
When you need to generate **multiple different images** in one go (e.g. a set
of blog heroes, several icon variations with different prompts, OG images for
many pages), use `--batch` instead of running the script N times. It runs all
jobs in parallel from a single Python process — much faster than serial calls
and avoids repeated SDK startup cost.
Write a JSON file describing every job, then call the script once:
```bash
cat > /tmp/img-jobs.json <<'EOF'
[
{
"prompt": "Minimal flat-vector app icon for a note-taking app, indigo gradient, rounded square",
"out": "./public/icons/notes.png",
"size": "1024x1024",
"quality": "high"
},
{
"prompt": "Photoreal blog hero: a cozy library with warm afternoon light, 5:3 ratio",
"out": "./public/static/blog/library.png",
"size": "1600x960",
"quality": "medium"
},
{
"prompt": "Restyle this product photo as a watercolor painting with warm tones",
"image": ["./public/products/mug.jpg"],
"out": "./public/products/mug-watercolor.png"
}
]
EOF
python3 ~/.cursor/skills/generating-images/scripts/generate_image.py \
--batch /tmp/img-jobs.json --concurrency 5
```
Each job object accepts the same fields as the CLI flags: `prompt` (required),
`out`, `size`, `quality`, `format`, `n`, `image` (string or array of strings),
`mask`. Defaults match the single-shot CLI.
Behavior:
- All jobs run concurrently up to `--concurrency` (default 4). A reasonable
range is 38; OpenAI rate-limits per org so don't go too wild.
- Each successfully written image's absolute path is printed to stdout as soon
as that job finishes, one per line.
- If any job fails, its error is printed to stderr (`ERROR: job <i> failed: ...`)
and the script exits with code 1 **after** the remaining jobs finish. Other
jobs are not cancelled — partial output is fine and you can retry only the
failed ones.
- `--batch` is mutually exclusive with `--prompt` / `--image` / `--mask`.
**When to prefer `--batch` over parallel Shell calls:** any time you're
generating ≥2 distinct images in the same turn. Don't fire multiple parallel
Shell invocations of this script — use one batch call instead.
**Don't confuse with `--n`.** `--n` produces multiple variations of the *same*
prompt in a single API call (cheaper, but all the same idea). `--batch` runs
*different* prompts in parallel. They can be combined: a batch job can set
`"n": 4` to get 4 variations of that one prompt.
## Flags reference
| Flag | Default | Notes |
|------|---------|-------|
| `--prompt` | required* | Required unless `--batch` is used. Always include, even when editing. |
| `--image` | none | Pass multiple times for multiple references. Triggers `images.edit`. |
| `--mask` | none | Optional inpainting mask (PNG with alpha). |
| `--out` | `./image.png` | Output path; index suffix added when `--n > 1`. |
| `--size` | `auto` | `1024x1024`, `1536x1024`, `1024x1536`, `2048x2048`, `3840x2160`, etc. Edges must be multiples of 16, max 3840px, ratio ≤ 3:1. |
| `--quality` | `auto` | `low` (fast drafts), `medium`, `high` (final assets). |
| `--format` | `png` | `png`, `jpeg`, `webp`. |
| `--n` | `1` | Variations of the SAME prompt in one call. |
| `--batch` | none | Path to JSON array of job objects; runs them in parallel. |
| `--concurrency` | `4` | Max parallel workers in `--batch` mode. |
There is intentionally **no `--model` flag**. The model is hardcoded to
`gpt-image-2`.
## Sizing guidance
- App icons / square thumbnails → `1024x1024`
- Landing-page heroes / OG images → `1536x1024`
- Blog hero (5:3) → `1600x960` (both edges multiples of 16, ratio = 5:3)
- Mobile / portrait illustrations → `1024x1536`
- Marketing posters / 4K assets → `3840x2160`
## Quality guidance
- `low` for quick exploration / drafts (cheapest, fastest).
- `medium` is a good default.
- `high` only for final, ship-ready assets — significantly more expensive
and can take up to ~2 minutes.
If the user just says "generate an image" with no signal of finality, default
to `--quality medium`.
## Prompt-writing tips
For best results, include in the prompt:
- Subject (what is in the image)
- Style (flat vector, watercolor, photoreal, isometric, line drawing, 3D render…)
- Composition / camera (close-up, top-down, wide shot)
- Color palette / mood
- Background (white, gradient, scene — note: `gpt-image-2` does not support
transparent backgrounds)
- Any text that must appear, in quotes (`gpt-image-2` renders text well)
If the user gives a vague prompt, expand it with sensible defaults rather than
asking back, unless the request is genuinely ambiguous.
## After generating
1. Print the output path back to the user.
2. Do **not** embed the image in markdown — Cursor displays generated files
automatically when they are written into the workspace.
3. If the result is meant for a website/app, consider also running it through
an optimizer (e.g. `pngquant`, `cwebp`) when file size matters.
## Gather context BEFORE generating
Unless the user has spelled out exactly what they want (subject, style, palette,
size, destination), do a quick context-gathering pass first. The goal is for
the generated image to feel like it belongs where it's going, not like a
random asset dropped into the project. Skipping this step is the #1 way this
skill produces off-brand results.
Things to look at, in roughly this order:
1. **Sibling images at the destination.** If the image will live in
`public/static/blog/`, `public/static/marketing/`, `assets/`, etc., open
one or two existing images in that folder with the Read tool. Match their:
- Illustration style (3D cartoon, flat vector, photoreal, line art, isometric…)
- Color palette and lighting
- Subject conventions (e.g. "always features the product mascot", "always a
metaphor, never literal screenshots", etc.)
- Aspect ratio and resolution
2. **The surface that will display it.** Read the relevant file:
- Blog post → read the MDX/Markdown (title, tags, opening paragraphs, key metaphors).
- Landing page section → read the component, headline, and surrounding copy.
- README → read the top of the README.
- Component → read the component to understand what it represents.
Pull the image's *meaning* from the actual content, not just the filename.
3. **Brand / design tokens.** If the project has a clearly defined palette,
logo, or mascot, mirror them. Quick places to check:
- `tailwind.config.*` for brand colors
- `globals.css` / theme files for CSS variables
- `public/` for logos / mascot assets
- Any existing OG images or marketing assets
4. **Aspect ratio / size.** Pick `--size` based on the surface:
blog hero, OG image, square avatar, mobile portrait, etc. Match what's
already there.
Then write the prompt incorporating what you learned: subject pulled from the
content, style + palette pulled from sibling assets and brand tokens,
composition matched to the surface.
If the user *did* give explicit direction (style, colors, exact subject),
honor it and skip context-gathering. If they gave partial direction, gather
context for the parts they left open.
Don't ask the user clarifying questions for things you can reasonably infer
from the codebase — infer first, ask only when something is genuinely
ambiguous (e.g. two equally valid styles already exist in the project).
## Place it AND wire it up — don't just dump a file
When the user asks for an image for a specific surface (a blog post, a landing
page, an OG card, a README, a component, etc.), you are responsible for the
whole job, not just the PNG. Always do these in order:
1. **Pick the correct on-disk location** for that surface. Look at what already
exists and match it. Examples:
- Blog hero → wherever existing blog images live (e.g.
`apps/<app>/public/static/blog/<slug>.png`).
- Landing page asset → wherever other landing assets live (e.g.
`apps/<app>/public/static/marketing/...`).
- README / docs image → `docs/images/`, `assets/`, or next to the doc.
- Component-specific asset → next to the component or in its
`public/`/`assets/` folder.
Use the file's slug, component name, or section name for the filename. Don't
invent a new convention if one already exists.
2. **Wire the image up** so it actually shows where the user wanted it. This is
not optional. Examples:
- Blog post MDX → update the `image:` (or equivalent) frontmatter field to
point at the new path. Replace any placeholder Unsplash/stock URL.
- Landing page section → import or reference the new asset in the relevant
component/JSX.
- OG image → update the `<meta property="og:image">` / metadata config.
- README → add the appropriate Markdown image tag.
3. **Match existing conventions** for paths (relative vs `/static/...` vs
`@/assets/...`), file format (png/webp/jpg), and any wrapper components
(`next/image`, custom `<Image>`, etc.).
4. **Don't ask first.** If the user asked for an image for a known surface, do
the placement + wiring automatically and tell them what you changed at the
end. Only ask when the destination is genuinely ambiguous.
## Errors — surface, don't hide
If any of the following happen, **stop immediately** and report the error to
the user. Do not retry, do not change the model, do not change the prompt.
- `OPENAI_API_KEY is not set` → ask the user how to provide it.
- `openai package not installed` → tell the user to run `pip install --upgrade openai`.
- 403 "organization must be verified" → tell the user to verify at
[platform.openai.com/settings/organization/general](https://platform.openai.com/settings/organization/general).
Do not switch models.
- 400 size error → report it; let the user pick a valid size.
- 400 about transparent background → report it; `gpt-image-2` doesn't
support transparency.
- Any other API error → report verbatim and stop.

View File

@ -1,247 +0,0 @@
#!/usr/bin/env python3
"""
Generate or edit images via OpenAI's gpt-image-2 model.
This script ALWAYS uses gpt-image-2. There is no fallback model and no way
to override it. If anything goes wrong (missing key, missing package, API
error, etc.) it exits immediately with a non-zero status. Do not silently
recover.
Usage:
# Single image from prompt
generate_image.py --prompt "a serene winter landscape" --out ./out.png
# Edit / use one or more reference images (also requires a prompt)
generate_image.py --prompt "make it look like a watercolor painting" \\
--image ./photo.png --out ./out.png
generate_image.py --prompt "combine these into a flat-lay product shot" \\
--image ./a.png --image ./b.png --image ./c.png --out ./combined.png
# Batch / parallel mode: run many distinct jobs concurrently
generate_image.py --batch ./jobs.json --concurrency 5
# Optional knobs
--size 1024x1024 | 1536x1024 | 1024x1536 | 2048x2048 | 3840x2160 | auto
--quality low | medium | high | auto
--format png | jpeg | webp
--n 1 # variations of the SAME prompt in one call
--concurrency 4 # parallel workers in --batch mode
Batch file format (JSON array of jobs):
[
{
"prompt": "...",
"out": "./a.png",
"size": "1024x1024",
"quality": "high",
"format": "png",
"n": 1,
"image": ["./ref1.png", "./ref2.png"],
"mask": "./mask.png"
},
{ "prompt": "...", "out": "./b.png" }
]
Each job uses the same defaults as the single-shot CLI when fields are omitted.
Requires: OPENAI_API_KEY in env, and `pip install openai>=1.x`.
"""
from __future__ import annotations
import argparse
import base64
import json
import os
import sys
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from typing import Any
MODEL = "gpt-image-2"
_print_lock = threading.Lock()
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(
description="Generate or edit images with OpenAI gpt-image-2. "
"Always uses gpt-image-2; fails fast on any error."
)
p.add_argument("--prompt", help="Text prompt describing the image. Required unless --batch is used.")
p.add_argument(
"--image",
action="append",
default=[],
help="Path to a reference image. Pass multiple times for multiple inputs. "
"If provided, uses the edits endpoint.",
)
p.add_argument("--mask", help="Optional mask PNG (must match first image size, with alpha channel).")
p.add_argument("--out", default="./image.png", help="Output file path. For --n>1, an index suffix is added.")
p.add_argument("--size", default="auto", help="Image size, e.g. 1024x1024 or 'auto'.")
p.add_argument("--quality", default="auto", choices=["low", "medium", "high", "auto"])
p.add_argument("--format", dest="output_format", default="png", choices=["png", "jpeg", "webp"])
p.add_argument("--n", type=int, default=1, help="Number of variations of the same prompt to generate in one call.")
p.add_argument(
"--batch",
help="Path to a JSON file describing multiple jobs. Each job runs in parallel. "
"Mutually exclusive with --prompt/--image/--mask/--out.",
)
p.add_argument(
"--concurrency",
type=int,
default=4,
help="Max parallel workers in --batch mode (default 4).",
)
return p.parse_args()
def die(msg: str, code: int = 1) -> "None":
print(f"ERROR: {msg}", file=sys.stderr)
sys.exit(code)
def write_image(b64: str, out_path: Path, idx: int, total: int) -> Path:
if total > 1:
out_path = out_path.with_name(f"{out_path.stem}_{idx + 1}{out_path.suffix}")
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_bytes(base64.b64decode(b64))
return out_path
def run_job(client: Any, job: dict) -> list[Path]:
"""Run a single image job and return the written paths."""
prompt = job.get("prompt")
if not prompt:
raise ValueError("job missing 'prompt'")
out = job.get("out", "./image.png")
size = job.get("size", "auto")
quality = job.get("quality", "auto")
output_format = job.get("format", "png")
n = int(job.get("n", 1))
images = job.get("image") or []
if isinstance(images, str):
images = [images]
mask = job.get("mask")
common: dict[str, Any] = {
"model": MODEL,
"prompt": prompt,
"size": size,
"quality": quality,
"n": n,
}
if output_format != "png":
common["output_format"] = output_format
open_files: list = []
try:
if images:
files = [open(p, "rb") for p in images]
open_files.extend(files)
kwargs = dict(common, image=files if len(files) > 1 else files[0])
if mask:
mf = open(mask, "rb")
open_files.append(mf)
kwargs["mask"] = mf
result = client.images.edit(**kwargs)
else:
result = client.images.generate(**common)
finally:
for f in open_files:
try:
f.close()
except Exception:
pass
out_base = Path(out)
written: list[Path] = []
for idx, item in enumerate(result.data):
b64 = item.b64_json
if not b64:
raise RuntimeError(f"image {idx} for out={out} returned no b64_json payload.")
written.append(write_image(b64, out_base, idx, len(result.data)))
if not written:
raise RuntimeError(f"API returned no images for out={out}.")
return written
def main() -> int:
args = parse_args()
if not os.environ.get("OPENAI_API_KEY"):
die("OPENAI_API_KEY is not set in the environment. Aborting.", code=2)
try:
from openai import OpenAI
except ImportError:
die("openai package not installed. Run: pip install --upgrade openai", code=2)
client = OpenAI()
if args.batch:
if args.prompt or args.image or args.mask:
die("--batch is mutually exclusive with --prompt/--image/--mask.", code=2)
try:
jobs = json.loads(Path(args.batch).read_text())
except Exception as e:
die(f"failed to read --batch file {args.batch}: {e}", code=2)
if not isinstance(jobs, list) or not jobs:
die("--batch file must contain a non-empty JSON array of job objects.", code=2)
concurrency = max(1, int(args.concurrency))
all_paths: list[Path] = []
first_error: BaseException | None = None
with ThreadPoolExecutor(max_workers=concurrency) as ex:
futures = {ex.submit(run_job, client, job): i for i, job in enumerate(jobs)}
for fut in as_completed(futures):
i = futures[fut]
try:
paths = fut.result()
except BaseException as e:
if first_error is None:
first_error = e
with _print_lock:
print(f"ERROR: job {i} failed: {e}", file=sys.stderr)
continue
with _print_lock:
for path in paths:
print(str(path.resolve()))
all_paths.extend(paths)
if first_error is not None:
return 1
if not all_paths:
die("batch produced no images.")
return 0
if not args.prompt:
die("--prompt is required (or use --batch).", code=2)
job = {
"prompt": args.prompt,
"out": args.out,
"size": args.size,
"quality": args.quality,
"format": args.output_format,
"n": args.n,
"image": list(args.image),
"mask": args.mask,
}
try:
written = run_job(client, job)
except Exception as e:
die(str(e))
for path in written:
print(str(path.resolve()))
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@ -1,69 +0,0 @@
---
name: grinding-until-pass
description: Keep iterating on code changes until the tests pass, the build succeeds, or linting is clean. Runs in a tight loop of fix → run → check → repeat. Use when you want the agent to autonomously grind through test failures or build errors.
---
# Grind Until Pass
Use this skill when you want the agent to keep working autonomously until a specific goal is met — all tests pass, the build succeeds, or linting is clean. Instead of stopping after one attempt, the agent loops until done.
## Steps
1. **Define the goal command** — the command whose exit code determines success:
- Tests: `npm test` or `npx vitest run`
- Build: `npm run build`
- Lint: `npm run lint`
- Type-check: `npx tsc --noEmit`
- All of the above: `npm run lint && npx tsc --noEmit && npm test && npm run build`
2. **Run the command** — execute it and capture the output.
3. **If it fails — analyze and fix**:
- Read the error output carefully.
- Identify the root cause: failing test assertion, type error, lint violation, import error, etc.
- Make the minimal fix. Don't refactor — just fix the error.
- Go back to step 2.
4. **If it passes — stop and report**:
- Report what was fixed and how many iterations it took.
- Summarize the changes made.
## Rules for the Loop
- **Maximum 10 iterations** — if after 10 attempts the command still fails, stop and report what's blocking progress. Something fundamental is wrong and needs human input.
- **Fix one thing at a time** — don't try to fix all errors at once. Fix the first error, re-run, and see if the fix resolves downstream errors too.
- **Don't delete tests** — if a test is failing, fix the code to make it pass. Don't modify the test unless the test itself is clearly wrong (testing old behavior that was intentionally changed).
- **Don't suppress errors** — don't add `@ts-ignore`, `eslint-disable`, or `any` types to silence errors. Fix the actual problem.
- **Track progress** — if the number of errors is increasing instead of decreasing, stop and reassess the approach.
## When to Use This
- After a large refactor that broke multiple tests
- After upgrading a dependency that introduced type errors
- After merging a branch with conflicts that need resolution
- When you want to "just make it green" and trust the agent to grind through it
## Advanced: Cursor Hooks Integration
You can automate this with a Cursor hook in `.cursor/hooks.json` that triggers after the agent's turn ends, checks if tests pass, and sends a follow-up message if they don't:
```json
{
"hooks": [
{
"event": "stop",
"command": "bash .cursor/scripts/check-tests.sh",
"description": "Re-run tests after agent stops and send follow-up if failing"
}
]
}
```
The script checks the exit code and returns a `followup_message` if tests are still failing.
## Notes
- This works best with fast test suites. If your tests take 5+ minutes, the loop will be slow.
- Use `--bail` or `--fail-fast` flags to stop at the first failure for faster iteration.
- The agent will be thorough but not creative — if the fix requires a design change, it'll need human guidance.

View File

@ -1,103 +0,0 @@
---
name: incident-response
description: Handle production incidents — triage, mitigate, communicate, and write postmortems.
user-invocable: true
---
# Incident Response
Handle production incidents systematically.
## Severity Levels
| Level | Definition | Response Time | Examples |
|-------|-----------|---------------|----------|
| SEV1 | Service down, all users affected | Immediate | Database crash, DNS failure, auth broken |
| SEV2 | Major feature broken, many users affected | < 30 min | Payments failing, search not working |
| SEV3 | Minor feature broken, workaround exists | < 4 hours | Export button broken, slow dashboard |
| SEV4 | Cosmetic or low-impact issue | Next business day | Typo in UI, minor styling bug |
## Incident Workflow
### 1. Detect & Triage (first 5 minutes)
- Acknowledge the incident — "I'm looking into this"
- Determine severity level
- Check monitoring dashboards (error rates, latency, status page)
- Check recent deployments: `git log --oneline -10` — was anything deployed recently?
### 2. Mitigate (next 15-30 minutes)
**The goal is to stop the bleeding, not find the root cause.**
Quick mitigations:
- **Rollback**: `git revert <commit> && deploy` — fastest option if a deploy caused it
- **Feature flag**: Disable the broken feature
- **Scale up**: Add more instances if it's a capacity issue
- **Failover**: Switch to backup/secondary if primary is down
- **Block traffic**: Rate-limit or block specific abusive traffic
### 3. Communicate
**Internal:**
- Open an incident channel (`#incident-2026-04-10`)
- Post status updates every 15-30 minutes
- Assign roles: Incident Commander, Communicator, Engineers
**External:**
- Update status page
- Send email/notification to affected users if the outage is extended
- Be honest: "We're experiencing issues with X. We've identified the cause and are working on a fix."
### 4. Resolve
- Deploy the fix
- Verify the fix works in production (check metrics, not just absence of errors)
- Close the incident channel with a summary
### 5. Postmortem (within 48 hours)
Write a blameless postmortem:
```markdown
# Incident: Payments failing for Stripe webhook
**Date:** 2026-04-10
**Duration:** 45 minutes (14:30 — 15:15 UTC)
**Severity:** SEV2
**Impact:** ~200 users unable to complete purchases
## Timeline
- 14:30 — Alert fires: payment success rate drops to 20%
- 14:35 — On-call engineer acknowledges, begins investigation
- 14:40 — Identified: Stripe webhook endpoint returning 500
- 14:45 — Root cause: migration added NOT NULL column without default
- 14:50 — Fix deployed: added default value to migration
- 15:00 — Payment success rate recovering
- 15:15 — Metrics back to normal, incident closed
## Root Cause
Database migration #47 added a `currency` column with NOT NULL
but no DEFAULT value. Existing rows were fine (backfilled), but
new webhook events failed because the insert didn't include `currency`.
## What Went Well
- Alert fired within 5 minutes of the issue starting
- Rollback was considered but the fix was faster
## What Went Wrong
- Migration wasn't tested with live webhook payloads
- No staging test for the webhook flow
## Action Items
- [ ] Add webhook integration test to CI (@alice, due 2026-04-17)
- [ ] Require DEFAULT for all new NOT NULL columns in migration review (@bob)
- [ ] Add runbook for payment failures (@charlie, due 2026-04-14)
```
## Tips
- Rollback first, investigate later — speed matters more than elegance
- The most recent deploy is the most likely cause
- Don't assign blame in postmortems — focus on process improvements
- Maintain a runbook for common failure modes
- Practice incident response with game days before real incidents happen

View File

@ -1,217 +0,0 @@
---
name: kubernetes-deploying
description: Deploy applications to Kubernetes — Deployments, Services, Ingress, ConfigMaps, Secrets, health checks, and scaling.
user-invocable: true
---
# Kubernetes Deploying
Deploy and manage applications on Kubernetes.
## Core Resources
### Deployment
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
labels:
app: my-app
spec:
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-app
image: my-registry/my-app:v1.2.3
ports:
- containerPort: 3000
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 512Mi
livenessProbe:
httpGet:
path: /healthz
port: 3000
initialDelaySeconds: 10
periodSeconds: 30
readinessProbe:
httpGet:
path: /ready
port: 3000
initialDelaySeconds: 5
periodSeconds: 10
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: my-app-secrets
key: database-url
- name: NODE_ENV
value: production
```
### Service
```yaml
apiVersion: v1
kind: Service
metadata:
name: my-app
spec:
selector:
app: my-app
ports:
- port: 80
targetPort: 3000
type: ClusterIP
```
### Ingress
```yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: my-app
annotations:
cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
tls:
- hosts:
- app.example.com
secretName: my-app-tls
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: my-app
port:
number: 80
```
### ConfigMap & Secret
```yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: my-app-config
data:
LOG_LEVEL: info
FEATURE_FLAGS: '{"darkMode": true}'
---
apiVersion: v1
kind: Secret
metadata:
name: my-app-secrets
type: Opaque
stringData:
database-url: postgresql://user:pass@host:5432/db
api-key: sk-abc123
```
## Common Commands
```bash
# Apply manifests
kubectl apply -f k8s/
# Check deployment status
kubectl rollout status deployment/my-app
# View pods
kubectl get pods -l app=my-app
# View logs
kubectl logs -f deployment/my-app
# Execute into a pod
kubectl exec -it <pod-name> -- /bin/sh
# Scale
kubectl scale deployment/my-app --replicas=5
# Rollback
kubectl rollout undo deployment/my-app
# Port forward for local debugging
kubectl port-forward svc/my-app 3000:80
```
## Deployment Strategies
| Strategy | How | When |
|----------|-----|------|
| Rolling update (default) | Replace pods one at a time | Most deployments |
| Recreate | Kill all old pods, start new ones | When you can't run two versions simultaneously |
| Blue/green | Run two full environments, switch traffic | Need instant rollback |
| Canary | Route small % of traffic to new version | High-risk changes |
Rolling update config:
```yaml
spec:
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
```
## Health Checks
Always set both:
- **livenessProbe**: "Is the process healthy?" — restarts the pod if it fails
- **readinessProbe**: "Can it handle traffic?" — removes from service if it fails
Common probe types:
- `httpGet`: Hit an HTTP endpoint (most common)
- `exec`: Run a command in the container
- `tcpSocket`: Check if a port is open
## Horizontal Pod Autoscaler
```yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: my-app
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: my-app
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
```
## Tips
- Always set resource requests and limits
- Use namespaces to isolate environments (`dev`, `staging`, `prod`)
- Never put secrets in plaintext YAML committed to git — use Sealed Secrets, SOPS, or external secret managers
- Tag images with specific versions, never use `:latest` in production
- Set `PodDisruptionBudget` for high-availability workloads

View File

@ -1,63 +0,0 @@
---
name: monitoring-terminal-errors
description: Watch running terminal processes for crashes and stack traces. When an error appears, navigate to the failing file and line, diagnose, and fix it automatically.
user-invocable: true
---
# Monitoring Terminal Errors
Continuously watch a running process (dev server, test runner, build) for errors and fix them as they appear.
## Workflow
### 1. Identify the Terminal
List terminal files and find the one running the target process:
```bash
head -n 10 <terminals_folder>/*.txt
```
Look for terminals running dev servers (`npm run dev`, `pnpm dev`, `python manage.py runserver`, etc.).
### 2. Read Terminal Output
Read the full terminal file content. Search for error patterns:
- **Stack traces**: `at <function> (<file>:<line>:<col>)`
- **Node.js**: `Error:`, `TypeError:`, `ReferenceError:`, `ENOENT`, `ECONNREFUSED`
- **Python**: `Traceback (most recent call last):` followed by `File "<path>", line <n>`
- **React/Next.js**: `Unhandled Runtime Error`, `Error: ...`, `Module not found`
- **Build errors**: `ERROR in`, `Failed to compile`, `SyntaxError`
- **Vite**: `[vite] Internal server error:`
- **TypeScript**: `error TS\d+:`
### 3. Extract the Source Location
From the stack trace, extract:
- File path
- Line number
- Error message
For Node.js: `at functionName (/path/to/file.ts:42:10)`
For Python: `File "/path/to/file.py", line 42, in function_name`
### 4. Navigate and Fix
1. Read the identified file around the error line
2. Understand the error (missing import, type mismatch, undefined variable, etc.)
3. Apply the fix
4. Re-read the terminal file to confirm the server recovered (hot reload should pick it up)
### 5. Loop
If the server is still showing errors after the fix, repeat from step 2. Stop when:
- The terminal shows a clean "compiled successfully" or equivalent
- No new errors appear in the output
- You've made 5 attempts without resolution (report to user)
## Tips
- Check for `exit_code` in the terminal file footer — if present, the process has crashed entirely and needs a restart
- Some errors cascade — fix the first/root error and the rest often disappear
- For HMR errors, the fix might just be saving the file again to trigger a rebuild

View File

@ -1,59 +0,0 @@
---
name: network-request-auditing
description: After navigating and interacting in Cursor's built-in browser, use browser_network_requests to audit every fetch/XHR for failures, slowness, duplicate calls, and suspicious payloads. Use for API-heavy pages and after backend or client networking changes.
user-invocable: true
---
# Network Request Auditing
Deep-dive **network** health using the `cursor-ide-browser` MCP. This skill focuses on `browser_network_requests` — not just “any 500s” but patterns that indicate bugs, waste, or security issues.
## How it works
1. Drive the app in the browser (navigate, click, submit forms) so real requests fire.
2. Call **`browser_network_requests`** after meaningful interactions (and after navigation settles).
3. Classify and report findings using the criteria below.
Follow `cursor-ide-browser` workflow rules: use `browser_snapshot` before structural interactions; after actions that change the page, take a fresh snapshot before the next interaction.
## Audit checklist
### Failures
- **4xx / 5xx** — list method, URL (path + query), status, and whether the UI handled the error.
- **CORS or network errors** — often misconfigured origins or mixed content.
### Performance
- **Slow requests** — flag requests with high latency (e.g. > 500 ms server time if timings are visible; otherwise note unusually large waterfalls).
- **Duplicate calls** — same URL + method fired multiple times in one user action (often a React effect or missing deduplication).
- **Oversized payloads** — responses that look huge for what the UI needs (suggest pagination, field selection, or compression).
### Security and privacy
- **Sensitive data in URLs** — tokens or PII in query strings.
- **Missing auth** — API calls that should send credentials or bearer tokens but do not (compare with adjacent authenticated calls).
### Correctness
- **Unexpected hosts** — calls to third parties not documented for the feature (trackers, accidental leaks).
- **Preflight storms** — excessive OPTIONS requests may indicate wrong CORS caching or too many distinct origins.
## Steps
1. **Start from a clean navigation**`browser_navigate` to the target URL (or use an existing tab via `browser_tabs`).
2. **Exercise the feature** — interactions that trigger API usage (filters, infinite scroll, form save, modal open).
3. **Fetch network log**`browser_network_requests` after each logical step if the page does multiple round-trips.
4. **Report** — structured output:
- Summary counts (failed, slow, duplicate groups).
- Table or bullet list of issues with **URL pattern** (not necessarily full secrets), **status**, **category** (failure / perf / security / correctness).
- Recommended next code changes or investigations.
## Notes
- Iframe traffic may not appear in the same log — note if the feature runs inside an iframe.
- Compare against **expected** API design; a 404 might be correct for “optional resource not found” if handled in UI.
- Pair with `browser_console_messages` for errors that do not surface as failed HTTP (e.g. parse errors after 200).

View File

@ -1,89 +0,0 @@
---
name: parallel-ci-triage
description: When GitHub Actions fails, fetch failing job logs and assign each failing job to a separate subagent that fixes its slice of the problem in parallel. Use for multi-job CI failures where jobs are independent.
user-invocable: true
---
# Parallel CI Triage
Speed up fixing broken CI by splitting failing **jobs** (or independent failure clusters) across parallel subagents. Each subagent owns one vertical slice: logs, root cause, code fix, and local verification for that slice.
## Prerequisites
- **GitHub CLI** (`gh`) installed and authenticated (`gh auth login`), or use the GitHub web UI / API to copy logs manually.
- Push access to the repo so fixes can be pushed and CI re-run.
## Workflow
### 1. Identify the failing run
From the repo root:
```bash
gh run list --limit 5
gh run view <RUN_ID> --log-failed
```
Or open the Actions tab, open the failed workflow run, and note which **jobs** failed (not just which step — group by job name).
If `gh` is unavailable, download logs from the GitHub UI and paste them into the conversation.
### 2. Split by job (or by failure cluster)
- **One subagent per failed job** when jobs test different things (e.g. `lint`, `test-node-18`, `e2e`).
- **One subagent per independent failure cluster** when a single job logs multiple unrelated errors — but prefer one job per agent to avoid conflicting edits in the same files.
If two failures share the same root cause in the same file, assign **one** subagent to fix both.
### 3. Launch parallel subagents
For each failing job, launch a `generalPurpose` subagent in a **single message** so they run concurrently:
```
Task: Fix CI failure for job "<JOB_NAME>"
Context:
- Workflow run: <RUN_URL or RUN_ID>
- Branch: <branch>
- Relevant log excerpt (failed steps only):
<paste gh run view --job <JOB_ID> --log or the failed section>
Instructions:
1. Infer the root cause from the log (command, stack trace, file:line).
2. Open and edit only what this job requires.
3. Run the same commands locally that failed in CI (or the narrowest equivalent, e.g. `npm run lint`, `pytest tests/foo`, `pnpm test --filter pkg`).
4. Report: what failed, what you changed, and confirmation that the local command passes.
```
Include the **exact** failing command and error lines so the subagent does not guess.
### 4. Merge and verify
- Collect each subagents changed files. Resolve overlaps manually if two agents touched the same file.
- Run the full CI-equivalent locally when possible:
```bash
# Example: match your repo
npm run lint && npm test
```
- Commit with a conventional message, push, and re-check the workflow:
```bash
gh run watch
```
## When to use
- Multiple GitHub Actions jobs failed and the failures look independent.
- A long workflow log is easier to split by job than to fix sequentially.
## When not to use
- A single job with one clear error — fix it in the main agent.
- Failures that are purely flaky infrastructure — retry or fix workflow config first.
## Notes
- Redact secrets if pasting logs into chat.
- If agents conflict on shared files, merge sequentially after the parallel pass.

View File

@ -1,104 +0,0 @@
---
name: parallel-code-review
description: Run four parallel read-only subagents that each review the same diff from a different lens — security, performance, correctness, and readability — then merge findings into one report. Use before merging large or risky PRs.
user-invocable: true
---
# Parallel Code Review
Use Cursors **Task** tool to run **four** `explore` (read-only) subagents at once. Each subagent only reads code and produces findings for one dimension. The main agent merges results into a single prioritized review — something only a multi-agent setup does efficiently.
## When to use
- Large diffs or refactors where a single pass misses categories.
- Security-sensitive changes (auth, payments, parsing untrusted input).
- Performance-sensitive paths (hot loops, N+1 queries, bundle entry points).
## Workflow
### 1. Scope the change set
Prefer a concrete list of files for reviewers:
```bash
git diff --name-only origin/main...HEAD
```
Or paste the PR link and let the main agent list changed files from the branch.
### 2. Launch four parallel subagents
Send **one message** with **four** Task invocations, each `subagent_type: "explore"` and **readonly: true**, with prompts like:
**Security**
```
Read-only review: SECURITY
Changed files:
<list>
Focus: injection (SQL, shell, XSS), authZ/authN gaps, secrets in code, unsafe deserialization, path traversal, SSRF, IDOR, dependency CVEs mentioned in diff.
Output:
- Critical / High / Medium / Low findings
- File:line and short fix recommendation
- "No issues" if nothing material
```
**Performance**
```
Read-only review: PERFORMANCE
Changed files:
<list>
Focus: N+1 queries, missing indexes, accidental O(n²) loops, bundle size impact, unnecessary re-renders, sync I/O on hot paths, unbounded caches.
Output: same severity + location format as above.
```
**Correctness**
```
Read-only review: CORRECTNESS
Changed files:
<list>
Focus: logic bugs, off-by-one, wrong edge cases, race conditions, error handling gaps, breaking API changes, test gaps for new behavior.
Output: same format.
```
**Readability / maintainability**
```
Read-only review: READABILITY
Changed files:
<list>
Focus: naming, duplication, abstraction boundaries, file size, unclear control flow, missing types/docs where they would prevent bugs.
Output: same format; prefer suggestions over nitpicks.
```
### 3. Synthesize
The main agent should:
1. De-duplicate findings that appear in multiple dimensions (count once, worst severity).
2. Order by severity, then by fix cost.
3. Produce a short executive summary (5 bullets max) and a table or list of actionable items.
### 4. Optional — address findings
Fix in the main agent or spawn targeted **non-readonly** follow-up tasks only for approved items.
## Notes
- Keep prompts **read-only** so parallel runs never fight over writes.
- If the diff is huge, split by directory and run four reviewers **per directory** in a second wave — do not cram unrelated megadiffs into one pass.
- This complements human review; it does not replace compliance or security sign-off for regulated environments.

View File

@ -1,55 +0,0 @@
---
name: parallel-exploring
description: Explore a large codebase in parallel by launching multiple explore subagents that each investigate a different area simultaneously. Use when onboarding onto a new project, understanding architecture, or investigating a cross-cutting concern.
---
# Parallel Explore
Use this skill when you need to understand a large or unfamiliar codebase quickly — onboarding onto a new project, investigating how a feature works across layers, or mapping the architecture.
## How It Works
Cursor's `explore` subagent is a fast, read-only agent optimized for searching and reading code. You can launch multiple explore agents in a single message and they run concurrently, each investigating a different area.
## Steps
1. **Identify the areas to explore** — break the codebase into logical zones. For a typical full-stack app:
- Frontend: components, pages, routing, state management
- Backend: API routes, database models, middleware, auth
- Infrastructure: CI/CD, Docker, deployment config
- Shared: types, utilities, constants
2. **Launch parallel explore agents** — use the Task tool with `subagent_type: "explore"` for each area. Launch them all in one message:
```
Task 1: "Explore the frontend — find the main pages, routing setup, state management approach,
and UI component library. Check src/app/, src/components/, src/pages/. Report the
framework, router, styling approach, and key components."
Task 2: "Explore the backend — find the API routes, database setup, ORM, auth middleware,
and data models. Check src/server/, src/api/, lib/, prisma/. Report the framework,
database, auth strategy, and key endpoints."
Task 3: "Explore the infrastructure — find CI/CD config, Docker setup, deployment targets,
and environment variable management. Check .github/, docker*, *.config.*, .env*.
Report the deploy target, CI provider, and any IaC."
```
3. **Synthesize the results** — when all agents return, combine their findings into a coherent picture:
- Tech stack summary (frontend, backend, database, infra)
- Architecture diagram (describe the data flow)
- Key files and entry points
- Potential concerns or tech debt
## Other Use Cases
- **Cross-cutting investigation**: "Where is user authentication checked?" — launch agents to search the frontend (route guards), backend (middleware), and database (session storage) simultaneously.
- **Dependency audit**: launch agents to check different parts of the dependency tree for outdated packages, security issues, and unused imports.
- **Migration planning**: have agents simultaneously assess the frontend, backend, and tests to estimate the scope of a framework migration.
## Notes
- Explore agents are read-only — they can't modify files.
- Use `thoroughness: "very thorough"` in the prompt for comprehensive analysis.
- Each agent has its own context window, so they can each read many files without running out of space.
- For a single focused question, just use Grep or SemanticSearch directly — subagents are for broad exploration.

View File

@ -1,74 +0,0 @@
---
name: parallel-test-fixing
description: When multiple tests fail, assign each failing test file to a separate subagent that fixes it independently in parallel.
user-invocable: true
---
# Parallel Test Fixing
Speed up fixing a broken test suite by distributing failing tests across parallel subagents.
## Workflow
### 1. Run the Full Test Suite
```bash
npm test -- --no-coverage 2>&1 || true
```
Capture the output and extract all failing test files.
### 2. Group Failures
Parse the test output for failing files:
- Jest: `FAIL src/components/Button.test.tsx`
- Vitest: `FAIL src/utils/format.test.ts`
- Pytest: `FAILED tests/test_api.py::test_create_user`
Group by file — each file becomes one task.
### 3. Launch Parallel Subagents
For each failing test file, launch a `generalPurpose` subagent:
```
Task: Fix the failing tests in <file>
The test file is: <path>
The test command is: <command to run just this file>
The error output was:
<paste the relevant failure output>
Steps:
1. Read the test file and the source file it tests
2. Understand why each test is failing
3. Fix the source code (preferred) or update the test if the test is wrong
4. Run the single test file to confirm it passes
5. Report what you changed and why
```
Launch all subagents simultaneously — they work in parallel since each touches different files.
### 4. Collect Results
As each subagent completes, collect:
- Which tests were fixed
- What files were changed
- Whether the fix might conflict with another subagent's changes
### 5. Verify
Run the full test suite one more time to confirm everything passes:
```bash
npm test
```
If there are new failures (from conflicting fixes), resolve them sequentially.
## Tips
- If two failing tests share the same source file, assign them to the same subagent to avoid edit conflicts
- Set a timeout — if a subagent is stuck for 5+ minutes, check its progress
- For large test suites (50+ failures), batch into groups of 5-10 per subagent rather than one-per-file
- Use `best-of-n-runner` subagents if you want isolated worktrees for each fix attempt

View File

@ -1,69 +0,0 @@
---
name: profiling-performance
description: Profile a running web application's CPU performance using Cursor's built-in browser profiler. Captures call stacks, identifies slow functions, and suggests optimizations. Use when a page feels slow or janky.
---
# Performance Profile
Use this skill when a web application feels slow, janky, or unresponsive. Cursor's built-in browser has CPU profiling tools that capture real call stacks and timing data.
## How It Works
The `cursor-ide-browser` MCP provides `browser_profile_start` and `browser_profile_stop` tools that capture Chrome DevTools-format CPU profiles. Profile data is written to `~/.cursor/browser-logs/` as both raw JSON and a human-readable summary.
## Steps
1. **Ensure the app is running** — start the dev server if it isn't already running.
2. **Navigate to the slow page**:
```
Tool: browser_navigate
Arguments: { "url": "http://localhost:3000/slow-page" }
```
3. **Start profiling**:
```
Tool: browser_profile_start
```
4. **Reproduce the slow interaction** — use browser tools to trigger the slow behavior:
- Click buttons, scroll, type in inputs, navigate between pages
- Use `browser_click`, `browser_scroll`, `browser_fill` to interact
- Wait a few seconds for the interaction to complete
5. **Stop profiling**:
```
Tool: browser_profile_stop
```
This writes two files to `~/.cursor/browser-logs/`:
- `cpu-profile-{timestamp}.json` — raw Chrome DevTools profile
- `cpu-profile-{timestamp}-summary.md` — human-readable summary
6. **Analyze the results** — read both files. Key things to look for in the raw JSON:
- `profile.nodes[].hitCount` — how many samples hit each function
- `profile.nodes[].callFrame.functionName` — the function names
- `profile.samples.length` — total number of samples collected
Cross-reference with the summary to identify:
- Functions consuming the most CPU time
- Unexpected re-renders or layout thrashing
- Expensive third-party library calls
- Synchronous operations blocking the main thread
7. **Suggest fixes** — based on the profile data, recommend specific optimizations:
- Memoize expensive computations
- Debounce rapid event handlers
- Move heavy work to a Web Worker
- Lazy-load components or routes
- Virtualize long lists
## Notes
- Always read the raw `.json` profile to verify the summary — the summary can miss nuances.
- Profile in development mode first, but be aware that React dev mode adds overhead. For accurate measurements, profile a production build.
- Short profiles (2-5 seconds of interaction) are usually more useful than long ones.
- Compare before/after profiles to verify your optimization actually helped.

View File

@ -1,138 +0,0 @@
---
name: prompt-engineering
description: Write effective prompts for LLMs — structure, few-shot examples, chain-of-thought, system prompts, and output parsing.
user-invocable: true
---
# Prompt Engineering
Write prompts that get reliable, high-quality output from LLMs.
## Core Principles
1. **Be specific** — vague prompts get vague results
2. **Show, don't tell** — examples beat instructions
3. **Structure the output** — tell the model exactly what format you want
4. **Iterate** — prompts are code; test and refine them
## Techniques
### System Prompts
Set the model's role and constraints:
```
You are a senior code reviewer. Review the provided code for:
1. Security vulnerabilities
2. Performance issues
3. Readability problems
For each issue found, provide:
- Severity (critical/warning/info)
- Line number
- Description
- Suggested fix
If no issues are found, respond with "No issues found."
```
### Few-Shot Examples
Provide 2-3 examples of input → output:
```
Convert the user's natural language query to a SQL query.
Example 1:
Input: "How many users signed up last month?"
Output: SELECT COUNT(*) FROM users WHERE created_at >= DATE_TRUNC('month', NOW() - INTERVAL '1 month') AND created_at < DATE_TRUNC('month', NOW());
Example 2:
Input: "Show me the top 5 products by revenue"
Output: SELECT p.name, SUM(o.amount) as revenue FROM products p JOIN orders o ON o.product_id = p.id GROUP BY p.name ORDER BY revenue DESC LIMIT 5;
Now convert this query:
Input: "{user_query}"
Output:
```
### Chain-of-Thought
Ask the model to reason step by step:
```
Analyze this error and suggest a fix. Think step by step:
1. What does the error message mean?
2. What could cause this error?
3. What is the most likely root cause given the code context?
4. What is the fix?
```
### Structured Output
Request JSON or a specific format:
```
Respond with a JSON object matching this schema:
{
"summary": "string - one sentence summary",
"sentiment": "positive | negative | neutral",
"key_topics": ["string"],
"confidence": 0.0-1.0
}
```
### Constraints and Guardrails
```
Rules:
- Only use information from the provided context
- If you don't know the answer, say "I don't know" — do not guess
- Keep responses under 200 words
- Do not include any PII in your response
```
## Patterns for Code
**Code generation:**
```
Write a TypeScript function that {description}.
Requirements:
- {requirement 1}
- {requirement 2}
Use these libraries: {libraries}
Follow this pattern from the codebase: {example}
```
**Code transformation:**
```
Refactor this code to {goal}. Keep the same behavior.
Do not change the public API (function signatures, exports).
```
**Bug fixing:**
```
This code has a bug: {description of bug}
Error: {error message}
Fix the bug. Explain what caused it in a comment.
```
## Anti-Patterns
- **Too vague**: "Make this better" → Be specific about what "better" means
- **Too long**: Giant prompts with everything → Split into focused prompts
- **Contradictory**: "Be concise but thorough" → Pick one or define the tradeoff
- **No examples**: Complex formatting without showing what you want → Add 1-2 examples
- **Prompt injection risk**: Including raw user input without delimiting → Use clear delimiters like `<user_input>...</user_input>`
## Tips
- Temperature 0 for deterministic tasks (code, classification), 0.7+ for creative tasks
- Test prompts with edge cases, not just the happy path
- Version control your prompts — they're as important as code
- Use structured output (JSON) when parsing the response programmatically
- Shorter prompts often outperform longer ones if they're precise enough

View File

@ -1,99 +0,0 @@
---
name: python-tdd-with-uv
description: Test-driven development in Python using uv as the package manager. Covers the red-green-refactor cycle, vertical slicing, and uv project setup.
user-invocable: true
---
# Python TDD with uv
Write Python code test-first using `uv` for fast dependency and environment management.
## Setting Up the Project
1. Check if `uv` is installed: `uv --version`
2. If the project doesn't have a `pyproject.toml`, initialize:
```bash
uv init
```
3. Add pytest as a dev dependency:
```bash
uv add --dev pytest pytest-cov
```
4. Confirm the test runner works:
```bash
uv run pytest --co
```
## TDD Workflow — Vertical Slicing
Work in small cycles. Never write more than one failing test at a time.
### Planning Phase
Before writing code, answer:
1. What interface changes are needed? (functions, classes, APIs)
2. Which behaviors matter most? (prioritize critical paths)
3. Can we design for testability? (inject dependencies, avoid global state)
### The Cycle
```
RED → Write ONE failing test for the next behavior
GREEN → Write the MINIMUM code to make it pass
REFACTOR → Clean up without changing behavior
REPEAT
```
**Rules:**
- Never write implementation before a failing test exists
- Never write more than one failing test at a time
- Run `uv run pytest` after every change
- Tests must assert observable behavior, not implementation details
- Mocks should only be used at system boundaries (I/O, network, clock)
### Test File Structure
```python
# tests/test_<module>.py
class TestFeatureName:
"""Group related behaviors."""
def test_does_expected_thing_when_given_input(self):
result = function_under_test(input_value)
assert result == expected
def test_raises_when_given_invalid_input(self):
with pytest.raises(ValueError):
function_under_test(bad_input)
```
### Running Tests
```bash
uv run pytest # all tests
uv run pytest tests/test_foo.py # single file
uv run pytest -k "test_name" # by name pattern
uv run pytest --cov=src # with coverage
uv run pytest -x # stop on first failure
```
## uv Essentials
```bash
uv add <package> # add dependency
uv add --dev <package> # add dev dependency
uv remove <package> # remove dependency
uv sync # sync environment from lockfile
uv run <command> # run in managed environment
uv lock # regenerate lockfile
```
- Always use `uv run` to execute commands — never activate venvs manually
- Commit both `pyproject.toml` and `uv.lock`
## References
- [mattpocock/skills — TDD skill](https://github.com/mattpocock/skills) — vertical-slice TDD philosophy
- [nizos/tdd-guard](https://github.com/nizos/tdd-guard) — automated TDD enforcement via hooks
- [s2005/uv-skill](https://github.com/s2005/uv-skill) — uv workflow patterns

View File

@ -1,124 +0,0 @@
---
name: react-native-patterns
description: Build mobile apps with React Native and Expo — navigation, platform-specific code, performance, and native modules.
user-invocable: true
---
# React Native Patterns
Build production-quality mobile apps with React Native and Expo.
## Project Setup
**Expo (recommended for most projects):**
```bash
npx create-expo-app@latest my-app
cd my-app
npx expo start
```
**Bare React Native (when you need full native control):**
```bash
npx @react-native-community/cli init MyApp
```
Use Expo unless you need a custom native module that Expo doesn't support.
## Navigation
Use `expo-router` (file-based routing) or `@react-navigation/native`:
```
app/
├── _layout.tsx # Root layout (tabs, stack, drawer)
├── index.tsx # Home screen
├── (tabs)/
│ ├── _layout.tsx # Tab navigator
│ ├── home.tsx
│ ├── profile.tsx
│ └── settings.tsx
└── [id].tsx # Dynamic route
```
## Platform-Specific Code
```typescript
import { Platform } from 'react-native';
const styles = StyleSheet.create({
shadow: Platform.select({
ios: { shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1 },
android: { elevation: 4 },
}),
});
```
For larger differences, use platform-specific files:
- `Component.ios.tsx`
- `Component.android.tsx`
## Styling
Use `StyleSheet.create` for performance (styles are sent to native once):
```typescript
const styles = StyleSheet.create({
container: { flex: 1, padding: 16 },
title: { fontSize: 24, fontWeight: '700' },
});
```
For a Tailwind-like experience, use `nativewind`:
```tsx
<View className="flex-1 p-4">
<Text className="text-2xl font-bold">Hello</Text>
</View>
```
## Performance
**FlatList over ScrollView** for long lists:
```tsx
<FlatList
data={items}
keyExtractor={(item) => item.id}
renderItem={({ item }) => <ItemRow item={item} />}
initialNumToRender={10}
maxToRenderPerBatch={5}
windowSize={5}
/>
```
**Memoize expensive components:**
```tsx
const ItemRow = React.memo(({ item }: { item: Item }) => (
<View><Text>{item.name}</Text></View>
));
```
**Avoid:**
- Inline styles (creates new objects every render)
- Anonymous functions in `renderItem`
- Large images without caching (`expo-image` handles this)
## Common Libraries
| Need | Library |
|------|---------|
| Navigation | `expo-router` or `@react-navigation/native` |
| State | `zustand`, `jotai`, or React context |
| Data fetching | `@tanstack/react-query` |
| Images | `expo-image` |
| Icons | `@expo/vector-icons` |
| Storage | `expo-secure-store` (sensitive), `@react-native-async-storage/async-storage` (general) |
| Animations | `react-native-reanimated` |
| Gestures | `react-native-gesture-handler` |
| Forms | `react-hook-form` + `zod` |
## Tips
- Test on both iOS and Android from the start, not at the end
- Use `expo-dev-client` for custom native modules with Expo
- Handle safe areas with `react-native-safe-area-context`
- Always handle keyboard avoidance for forms (`KeyboardAvoidingView`)
- Use `expo-updates` for OTA updates in production

View File

@ -1,79 +0,0 @@
---
name: recording-browser-flow-as-test
description: Execute a user flow step-by-step in Cursor's built-in browser while documenting each action, then emit a Playwright test that replays the same flow using stable selectors derived from the accessibility tree.
user-invocable: true
---
# Recording Browser Flow as Playwright Test
Use the **browser** MCP as a **recorder**: every navigation, click, fill, and keypress becomes a row in a script. The agent then translates that trace into a **Playwright** test file in the repo (or a snippet to paste into an existing spec).
This is Cursor-native because it combines `browser_snapshot` (refs + roles + names) with structured actions — not a separate recorder extension.
## Prerequisites
- Target app reachable (e.g. dev server running); use `finding-dev-server-url` if needed.
- Repo has or will have Playwright installed (`@playwright/test`). If not, add it with `adding-e2e-tests` or the projects standard setup.
## Recording workflow
### 1. Define the flow
One sentence scope, e.g. “Log in, open Settings, toggle dark mode, save.”
### 2. For each step, in order
1. **`browser_snapshot`** — get the accessibility tree and element refs.
2. Choose the **smallest** interaction:
- `browser_click` with ref from snapshot (not coordinate clicks unless required).
- `browser_fill` or `browser_type` for inputs.
- `browser_select_option` for selects.
- `browser_navigate` for full URL changes.
3. **Log the step** in a structured list the main agent keeps:
- Step number
- Action verb (`navigate`, `click`, `fill`, `press`, `select`)
- **Locator strategy for Playwright** — prefer:
- `getByRole('button', { name: '...' })`
- `getByLabel('...')`
- `getByPlaceholder('...')`
- `getByTestId('...')` if the app uses test IDs
- Value (for fills), URL (for navigates)
- Optional: short assertion (“expect URL to contain `/settings`”)
4. After actions that change the DOM or navigate, take a **new** `browser_snapshot` before the next interaction.
5. If the flow must wait for async content, use `browser_wait_for` or short incremental waits per `cursor-ide-browser` guidance — then snapshot again.
### 3. Add assertions
From the final snapshot and URL, add **at least**:
- `expect(page).toHaveURL(...)` or URL fragment check
- One **visible** outcome: text, role, or test id
### 4. Generate Playwright output
Emit a test file, e.g. `tests/recorded/<flow-name>.spec.ts`, containing:
- `test.describe` and `test('...', async ({ page }) => { ... })`
- Steps as `await page.goto(...)`, `await page.getByRole(...).click()`, etc.
- **No** raw snapshot refs in the final file — they are session-specific.
### 5. Run and harden
```bash
npx playwright test tests/recorded/<flow-name>.spec.ts
```
Fix flakiness: prefer `expect(locator).toBeVisible()` before clicks, use `toPass()` retries for async lists, avoid arbitrary `waitForTimeout` except as last resort.
## Tips
- **Stable selectors**: roles and accessible names beat CSS from devtools. Add `data-testid` in app code if names are ambiguous.
- **Auth**: if the flow needs login, use env vars for test credentials or Playwright `storageState` — never commit secrets.
- **Parallel runs**: ensure test data does not collide with other tests.
## When not to use
- Flows that require manual 2FA, captchas, or email links — stop and ask the user for a test bypass or mock.

View File

@ -1,60 +0,0 @@
---
name: responsive-testing
description: Open the app in Cursor's browser at multiple viewport sizes, screenshot each, and report any layout breakage.
user-invocable: true
---
# Responsive Testing
After a UI change, verify the app looks correct at all standard breakpoints.
## Viewports to Test
| Name | Width | Tailwind |
|------|-------|----------|
| Mobile (small) | 375px | default |
| Mobile (large) | 428px | default |
| Tablet | 768px | `md:` |
| Desktop | 1280px | `xl:` |
| Ultrawide | 1536px | `2xl:` |
## Workflow
### 1. Navigate to the Page
Use `browser_navigate` to open the target URL (usually `http://localhost:3000` or whatever the dev server is running on).
### 2. Test Each Viewport
For each viewport size:
1. Resize the viewport using `browser_navigate` with viewport parameters, or use `browser_snapshot` to inspect the layout
2. Take a screenshot with `browser_take_screenshot`
3. Check `browser_snapshot` for the aria tree — look for:
- Content overflowing or hidden behind other elements
- Navigation that should collapse into a hamburger menu
- Text that's too small to read
- Buttons/links too close together (touch target issues)
- Horizontal scrollbars that shouldn't exist
### 3. Check for Common Breakage
- **Overflow**: Elements wider than the viewport causing horizontal scroll
- **Collapsed layout**: Flex/grid items that should stack on mobile but don't
- **Hidden content**: Elements that disappear at certain sizes without a menu toggle
- **Font scaling**: Text that's readable on desktop but tiny on mobile
- **Fixed positioning**: Modals, toasts, or sticky headers that break on small screens
- **Images**: Oversized images that don't scale down
### 4. Report
```
Responsive Test Results:
375px (mobile): PASS — layout stacks correctly
428px (mobile): PASS
768px (tablet): WARN — nav items overlap, need hamburger menu
1280px (desktop): PASS
1536px (ultrawide): WARN — content not centered, stretched too wide
```
Fix any issues found, then re-test the affected viewports.

View File

@ -1,55 +0,0 @@
---
name: reviewing-code
description: Perform a thorough code review focused on correctness, maintainability, performance, and best practices.
---
# Code Review
Use this skill when the user asks for a code review, feedback on their code, or to check code quality.
## Steps
1. **Understand the change** — read the files or diff to understand what the code is supposed to do. Identify the scope (new feature, bug fix, refactor).
2. **Check correctness**
- Does the code handle edge cases (empty input, null, zero, negative numbers)?
- Are error states handled (try/catch, error boundaries, fallback UI)?
- Does async code handle race conditions, cancellation, and timeouts?
- Are there off-by-one errors in loops or array access?
3. **Check maintainability**
- Are functions focused on a single responsibility?
- Are variable and function names descriptive?
- Is there unnecessary duplication that should be extracted?
- Are magic numbers replaced with named constants?
- Is the code complexity reasonable (deeply nested conditionals, long functions)?
4. **Check performance**
- Are there N+1 query patterns in database access?
- Are expensive computations or API calls happening in render loops?
- Are large lists missing virtualization or pagination?
- Are there missing indexes for common database queries?
- Is memoization used appropriately (not over-applied)?
5. **Check type safety** (TypeScript projects)
- Are there `any` types that should be narrowed?
- Are function return types explicit for public APIs?
- Are union types handled exhaustively?
6. **Check testing**
- Are there tests for the new/changed code?
- Do tests cover the happy path AND error cases?
- Are tests isolated (no shared mutable state)?
7. **Provide feedback** — organize findings by severity:
- **Must fix**: bugs, security issues, data loss risks
- **Should fix**: performance issues, maintainability concerns
- **Nit**: style preferences, minor suggestions
For each finding, include the file, line, the issue, and a suggested fix.
## Notes
- Be constructive — explain *why* something is a problem, not just that it is.
- Acknowledge what's done well, not just what needs fixing.
- Don't bikeshed on style issues that a linter/formatter should handle.

View File

@ -1,115 +0,0 @@
---
name: saving-workspace-context
description: Automatically persist useful context — research, decisions, learnings, templates — to workspace files so knowledge survives across conversations.
user-invocable: false
---
# Saving Workspace Context
You are an agent that builds institutional memory. As you work, watch for information that should outlast this conversation and save it to the workspace so future sessions start smarter.
## At the Start of Every Conversation
Load existing context before doing anything else:
1. Check for a `context/` directory — read any files relevant to the current task
2. Check for a product/project context file (e.g. `.agents/product-marketing-context.md`, `PROJECT.md`, or similar) for positioning, goals, and constraints
3. Check for any domain-specific directories the project uses (e.g. `companies/`, `docs/`, `research/`)
4. Check for templates or reusable assets that might apply
If the project doesn't have a `context/` directory yet, that's fine — create one when you first have something worth saving.
## During a Conversation
Watch for information that should be persisted. Save it as soon as you recognize it — don't wait until the end.
| Signal | Where to Save |
|---|---|
| Product details, positioning, ICP changes | Project context file (e.g. `.agents/product-marketing-context.md`) |
| Research on a company, person, or topic | `context/{topic-slug}.md` or a domain-specific directory |
| Strategy decisions or learnings | `context/{topic}.md` with dated entries |
| Reusable templates or boilerplate | `templates/` or a project-appropriate location |
| A repeatable multi-step workflow | New skill in `.cursor/skills/` or `.agents/skills/` |
| A persistent constraint or convention | New rule in `.cursor/rules/` |
### How to Save
- **Don't ask permission** for small context saves — just do it and mention what you saved
- **Do ask permission** before creating new skills or rules (they affect all future conversations)
- **Append, don't overwrite** when adding to existing context files — use dated entries
- **Use clear file names** — future you (or a future agent) needs to find this by scanning a directory listing
## At the End of a Conversation
Before finishing, ask yourself:
- Did I learn anything about this project that isn't captured in workspace files?
- Did I do research that would be painful to redo?
- Did I discover a pattern that should become a skill or rule?
- Did I create content that could be templated for reuse?
If yes to any, save it before the conversation ends.
## File Formats
### Context Files (`context/{slug}.md`)
```markdown
# {Topic}
## {Date} — {Brief title}
{What was learned, decided, or discovered}
## {Earlier date} — {Earlier entry}
{Previous context}
```
Keep entries reverse-chronological (newest first). Date your entries so they age gracefully.
### Project Context File
A single file capturing the current state of the project's identity:
```markdown
# {Project Name} — Context
- **What it is:** {one line}
- **Who it's for:** {target audience}
- **Key differentiator:** {why this vs alternatives}
- **Current stage:** {pre-launch / beta / growth / etc.}
- **Current goals:** {what matters right now}
## Positioning
{How we talk about the product}
## Constraints
{Things to always keep in mind}
```
## When to Create a New Skill
Create a skill when you find yourself doing the same multi-step workflow more than once:
- Researching a topic (check multiple sources, synthesize, save findings)
- Preparing for a meeting or call (pull context, recent history, prep talking points)
- Running a campaign or process (select targets, personalize, track progress)
## When to Create a New Rule
Create a rule when a persistent constraint should apply across all conversations:
- Voice/tone guidelines that get refined through feedback
- Naming conventions or file organization patterns
- Domain-specific constraints ("never mention X", "always check Y first")
## Rules
- Be proactive — save context without being asked, but mention what you saved
- Keep files scannable — future agents will skim directory listings to find context
- Don't save trivial information — if it's easily re-derived, skip it
- Date everything that accumulates over time
- Check for existing files before creating new ones to avoid duplicates

View File

@ -1,74 +0,0 @@
---
name: screenshotting-changelog
description: Generate a visual changelog or PR description by taking before/after screenshots of UI changes using Cursor's built-in browser. Use when preparing a PR with visual changes.
---
# Screenshot Changelog
Use this skill when preparing a pull request that includes visual/UI changes. Capture before and after screenshots to create a visual changelog that reviewers can quickly scan.
## Steps
1. **Capture the "before" state** — before making changes (or on the base branch), start the dev server and screenshot the affected pages:
```bash
git stash # or checkout the base branch
```
Start the dev server, then:
```
Tool: browser_navigate
Arguments: { "url": "http://localhost:3000/affected-page", "take_screenshot_afterwards": true }
```
```
Tool: browser_take_screenshot
Arguments: { "fullPage": true, "filename": "before-homepage.png" }
```
Repeat for each affected page or component state.
2. **Switch to the feature branch** — apply your changes:
```bash
git stash pop # or checkout the feature branch
```
Wait for the dev server to hot-reload (or restart it).
3. **Capture the "after" state** — screenshot the same pages:
```
Tool: browser_take_screenshot
Arguments: { "fullPage": true, "filename": "after-homepage.png" }
```
4. **Generate the changelog** — create a summary describing what changed visually:
```markdown
## Visual Changes
### Homepage
**Before:**
![before](before-homepage.png)
**After:**
![after](after-homepage.png)
Changes: Updated hero section layout, new CTA button color, added testimonials section.
```
5. **Include in the PR description** — paste the visual changelog into the PR body so reviewers can see the changes at a glance without running the app locally.
## Variations
- **Responsive comparison**: use `browser_resize` to capture screenshots at mobile (375px), tablet (768px), and desktop (1280px) widths.
- **Dark mode comparison**: if the app has a dark mode toggle, capture both themes.
- **Interactive states**: capture hover states, open modals, filled forms, and error states.
## Notes
- Screenshots are saved to the workspace. You can reference them in markdown or upload them to the PR.
- For component-level screenshots, navigate to a Storybook URL or a specific component route.
- This is most valuable for design-heavy PRs — skip it for backend-only changes.

View File

@ -1,140 +0,0 @@
---
name: seo-auditing
description: Audit technical SEO — meta tags, structured data, Open Graph, sitemaps, robots.txt, performance, and accessibility signals.
user-invocable: true
---
# SEO Auditing
Check and fix technical SEO issues in a web project.
## Audit Checklist
### 1. Meta Tags
Every page must have:
```html
<head>
<title>Page Title — Site Name</title>
<meta name="description" content="155 chars max, compelling summary" />
<link rel="canonical" href="https://example.com/page" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
```
Check for:
- [ ] Unique `<title>` per page (50-60 chars)
- [ ] Unique `<meta description>` per page (120-155 chars)
- [ ] Canonical URL set (avoids duplicate content)
- [ ] No `noindex` on pages that should be indexed
### 2. Open Graph & Social
```html
<meta property="og:title" content="Page Title" />
<meta property="og:description" content="Description for social sharing" />
<meta property="og:image" content="https://example.com/og-image.png" />
<meta property="og:url" content="https://example.com/page" />
<meta property="og:type" content="website" />
<meta name="twitter:card" content="summary_large_image" />
```
- OG image should be 1200x630px
- Test with https://developers.facebook.com/tools/debug/ and https://cards-dev.twitter.com/validator
### 3. Structured Data (JSON-LD)
Add schema markup for rich search results:
```html
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Article",
"headline": "Article Title",
"author": { "@type": "Person", "name": "Author Name" },
"datePublished": "2026-04-10",
"image": "https://example.com/image.jpg"
}
</script>
```
Common types: `Article`, `Product`, `FAQPage`, `Organization`, `BreadcrumbList`
Test with: https://search.google.com/test/rich-results
### 4. Sitemap
`/sitemap.xml` should:
- List all indexable pages
- Include `<lastmod>` dates
- Exclude pages with `noindex`
- Be under 50MB / 50,000 URLs per file
- Be referenced in `robots.txt`
### 5. Robots.txt
`/robots.txt` should:
```
User-agent: *
Allow: /
Disallow: /api/
Disallow: /admin/
Sitemap: https://example.com/sitemap.xml
```
- Not block CSS/JS files (search engines need them to render)
- Not block pages you want indexed
### 6. Performance (Core Web Vitals)
| Metric | Good | Needs Work |
|--------|------|------------|
| LCP (Largest Contentful Paint) | < 2.5s | > 4.0s |
| INP (Interaction to Next Paint) | < 200ms | > 500ms |
| CLS (Cumulative Layout Shift) | < 0.1 | > 0.25 |
Key fixes:
- Compress and lazy-load images
- Preload critical fonts and CSS
- Avoid layout shifts from dynamic content
- Use `next/image` or equivalent for automatic optimization
### 7. Crawlability
- [ ] All important pages are reachable from internal links
- [ ] No orphan pages (pages with zero internal links)
- [ ] No redirect chains (A→B→C should be A→C)
- [ ] 404 pages return proper HTTP 404 status
- [ ] No broken internal links
### 8. Accessibility (SEO Signals)
- [ ] All images have `alt` text
- [ ] Heading hierarchy is correct (one `h1`, then `h2`, `h3` etc.)
- [ ] Links have descriptive text (not "click here")
- [ ] Language attribute set: `<html lang="en">`
## Quick Automated Check
```bash
# Check robots.txt
curl -s https://example.com/robots.txt
# Check sitemap
curl -s https://example.com/sitemap.xml | head -20
# Check meta tags
curl -s https://example.com | grep -E '<title>|<meta name="description"|<link rel="canonical"'
# Check HTTP status codes
curl -o /dev/null -s -w "%{http_code}" https://example.com/page
```
## Tips
- Run Lighthouse in Chrome DevTools → check SEO score
- Google Search Console is the source of truth for indexing issues
- Mobile-friendliness is a ranking factor — test on mobile viewports
- Page speed directly affects rankings — optimize Core Web Vitals

Some files were not shown because too many files have changed in this diff Show More