Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
d29ee79
feat(cursor): add CLI for validating cursor rules and commands
kzndotsh Dec 7, 2025
dd76629
feat(docs): add comprehensive documentation for code quality commands
kzndotsh Dec 7, 2025
8ac3bee
fix(cursor): update pre-commit hook entry for cursor validation
kzndotsh Dec 7, 2025
4839828
feat(rules): implement CLI for validating rules and commands
kzndotsh Dec 7, 2025
1b9b702
feat(rules): expand and organize Cursor rules and commands documentation
kzndotsh Dec 7, 2025
9bc584d
feat(templates): add command and rule templates for documentation
kzndotsh Dec 7, 2025
80e6bf3
feat(guides): add comprehensive guides for creating Cursor commands a…
kzndotsh Dec 7, 2025
80bec89
feat(cursor): add README for Cursor rules and commands
kzndotsh Dec 7, 2025
d032b74
feat(docs): enhance AGENTS.md with Cursor rules and commands overview
kzndotsh Dec 7, 2025
9181794
feat(docs): add new guides for creating Cursor rules and commands
kzndotsh Dec 7, 2025
94abd23
chore(pre-commit): update configuration to enhance commit message han…
kzndotsh Dec 7, 2025
f1bb4f8
feat(rules): refactor validation command structure and update documen…
kzndotsh Dec 30, 2025
6a8de68
feat(code-quality): introduce new deslop command for maintaining high…
kzndotsh Dec 30, 2025
99a490e
fix(validation): improve error handling and frontmatter validation in…
kzndotsh Dec 30, 2025
10f239e
fix(docs): update validation command in AGENTS.md for consistency
kzndotsh Dec 30, 2025
419f2a2
fix(docs): update command syntax in migration and development documen…
kzndotsh Dec 30, 2025
27ae21a
fix(validation): add support for large file exceptions in rule valida…
kzndotsh Dec 30, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions .cursor/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# Cursor Rules & Commands

The Tux project uses Cursor's rules and commands system to provide AI-assisted development with project-specific patterns and workflows.

## Overview

This directory contains:

- **Rules** (`.mdc` files) - Project-specific coding patterns and standards
- **Commands** (`.md` files) - Reusable workflows and task automation

Rules are automatically applied by Cursor based on file patterns, while commands are invoked manually with the `/` prefix in Cursor chat.

## Structure

### Rules

Rules are organized by domain in `.cursor/rules/`:

- **`core/`** - Core project rules (tech stack, dependencies)
- **`database/`** - Database layer patterns (models, migrations, controllers, services, queries)
- **`modules/`** - Discord bot modules (cogs, commands, events, permissions, interactions)
- **`testing/`** - Testing patterns (pytest, fixtures, markers, coverage, async)
- **`docs/`** - Documentation rules (Zensical, writing standards, structure)
- **`security/`** - Security patterns (secrets, validation, dependencies)
- **`error-handling/`** - Error handling (patterns, logging, Sentry, user feedback)
- **`ui/`** - UI components (Discord Components V2)
- **`meta/`** - System documentation (Cursor rules/commands specifications)

### Commands

Commands are organized by category in `.cursor/commands/`:

- **`code-quality/`** - Code quality workflows (lint, refactor, review)
- **`testing/`** - Testing workflows (run tests, coverage, integration)
- **`database/`** - Database workflows (migration, health, reset)
- **`discord/`** - Discord bot workflows (create module, test command, sync)
- **`security/`** - Security workflows (security review)
- **`debugging/`** - Debugging workflows (debug issues)
- **`error-handling/`** - Error handling workflows (add error handling)
- **`documentation/`** - Documentation workflows (generate, update, serve)
- **`development/`** - Development workflows (setup, docker)

## Usage

Rules are automatically applied by Cursor:

- **Always Apply** - Rules with `alwaysApply: true` are active in every chat
- **File-Scoped** - Rules with `globs` patterns apply when editing matching files
- **Intelligent** - Rules with `description` are selected by Cursor based on context

Commands are invoked manually:

1. Type `/` in Cursor chat
2. Select command from autocomplete list
3. Command executes with current context

Example: `/lint` runs the linting workflow

## Quick Reference

See [rules/rules.mdc](rules/rules.mdc) for a complete catalog of all rules and commands.

## Contributing

See the developer documentation for comprehensive guides on creating and maintaining rules/commands:

- [Creating Cursor Rules Guide](../docs/content/developer/guides/creating-cursor-rules.md)
- [Creating Cursor Commands Guide](../docs/content/developer/guides/creating-cursor-commands.md)

## Resources

- [Cursor Rules Documentation](https://cursor.com/docs/context/rules)
- [Cursor Commands Documentation](https://cursor.com/docs/agent/chat/commands)
- [AGENTS.md](../AGENTS.md)
148 changes: 148 additions & 0 deletions .cursor/commands/code-quality/deslop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
# Deslop

## Overview

Produce high-quality Python code following strict Tux project standards, avoiding AI-generated pitfalls. This command guides you through writing consistent, maintainable code free of "slop" - unnecessary complexity, inconsistencies, and anti-patterns.

## Steps

1. **Research-First Protocol (MANDATORY)**
- Read relevant docs - Search workspace (notes/, docs/, README). Use as context; verify against actual code.
- Read API documentation - Official docs, in-code comments. Use as context; verify against actual code.
- Map system end-to-end:
- Data Flow & Architecture: Request lifecycle, dependencies, integration points, affected components
- Data Structures & Schemas: Database schemas, API structures, validation rules
- Configuration & Dependencies: Environment variables, service dependencies, deployment configs
- Existing Implementation: Search for similar features - leverage or expand existing code instead of creating new
- Inspect existing code - Study implementations before building. If leveraging existing code, trace all dependencies first.
- Verify understanding - Explain system flow, data structures, dependencies, impact. Use structured thinking for complex problems.
- Check for blockers - Ambiguous requirements? Security/risk concerns? Multiple valid architectural choices? Missing critical info?

2. **Write Consistent Code**
- Match existing style - Use the same naming conventions, import style, and structure as the file.
- Follow established patterns - If controllers are used for DB access, use controllers. If services handle business logic, use services.
- Reuse existing code - Don't duplicate - check if utilities, helpers, or similar functions exist.
- Stay in scope - ONLY modify what's requested. Do NOT change unrelated code.
- Preserve patterns - If you see a pattern (e.g., `Type | None`, specific exception types), maintain it exactly.
- Use existing constants - Check for existing constants/config before using magic numbers/strings.

3. **Follow Python Standards**
- Type hints: ALWAYS use strict typing with `Type | None` syntax, NEVER `Optional[Type]`
- Docstrings: ALWAYS use NumPy format for all public APIs with Parameters, Returns, Raises, Examples sections
- Imports: Group as stdlib → third-party → local. Use absolute imports when possible
- Line length: Maximum 88 characters (ruff default)
- Naming: `snake_case` for functions/vars, `PascalCase` for classes, `UPPER_CASE` for constants
- File size: NEVER exceed 1600 lines per file - split if needed

4. **Database Layer Standards**
- Controllers: ALWAYS use controllers for business logic. NEVER bypass controllers for CRUD operations
- Single service: Use `DatabaseService` singleton pattern. NEVER create parallel DB clients
- Transactions: Use controller methods (`with_transaction`, `with_session`). NEVER use raw sessions for CRUD
- Models: ALWAYS inherit from `BaseModel`. Use mixins (`UUIDMixin`, `SoftDeleteMixin`) when appropriate
- Relationships: ALWAYS configure proper `back_populates`, appropriate `lazy` strategy, correct `cascade`
- Migrations: ALWAYS use Alembic (`uv run db dev`). NEVER make manual schema changes

5. **Service Layer Standards**
- Dependency injection: Services MUST receive dependencies via constructor, NEVER use globals
- Stateless: Services MUST be stateless where possible
- Async/await: ALL I/O operations MUST be async
- Error handling: Use custom exceptions from `TuxError` hierarchy, NEVER generic `Exception`
- Logging: Use `loguru` with appropriate context, NEVER `print()`
- Sentry: Integrate error tracking with `sentry-sdk` for production errors

6. **Discord Bot Patterns**
- Commands: Use hybrid commands (slash + traditional) when appropriate
- Cogs: Follow modular organization with proper `cog_load`/`cog_unload` lifecycle
- Permissions: ALWAYS check permissions before actions using the permission system
- Embeds: Use `discord.Embed` for user-facing messages with consistent formatting
- Rate limits: Handle Discord rate limits gracefully with retries/backoff
- Error messages: Use user-friendly messages via global error handler

7. **Review Before Submitting**
- Verify APIs - Check that all methods/functions you used actually exist in the libraries
- Check consistency - Ensure your code matches the style and patterns of the file
- Review scope - Verify you only changed what was requested - no extra "improvements"
- Check for slop - Review your code against anti-patterns (see Error Handling section)
- Remove debug code - Ensure no `print()`, temporary variables, or test code remains
- Verify patterns - Ensure you didn't break established patterns or conventions
- Verify against usage - Read the calling code to see what it expects. Ensure consumers get all fields/data they need.
- Adversarial verification - Actively try to falsify assumptions. Look for regressions, silent failures, edge cases.

8. **Mandatory Self-Audit**
- Run all relevant tests and show results
- Verify against actual usage (read calling code)
- Check for regressions or unintended side effects
- Verify all changes match requested scope
- Provide evidence (test output, code references, verification steps)
- Use status markers: ✅ (completed), ⚠️ (recoverable issue fixed), 🚧 (blocked after exhausting research)

## Error Handling

### Common Anti-Patterns to Avoid

**Python Anti-Patterns:**

- Bare `except:` - ALWAYS use `except Exception:` or specific exception types
- `Optional[Type]` - Use `Type | None` (Python 3.13+ syntax)
- Mutable default arguments - NEVER use mutable defaults (`[]`, `{}`, `set()`). Use `None` and check inside
- Direct session access - NEVER use `async with db.session() as session:` for CRUD - use controllers
- Synchronous I/O - NEVER use blocking I/O in async functions (`requests`, `open()` without `aiofiles`)
- Comparing to None - Use `is None` or `is not None`, NEVER `== None`
- Generic exceptions - Use specific `TuxError` subclasses, NEVER `Exception`
- Missing type hints - ALL function signatures MUST have type hints
- `# type: ignore` - Fix type errors properly, NEVER suppress them
- `print()` statements - Use `loguru` logger, NEVER `print()`

**AI Code Slop Detection:**

- Extra comments inconsistent with file style
- Over-defensive programming: unnecessary `| None` unions, excessive null checks
- Type system abuse: Using `cast(Any, ...)` or `# type: ignore` to get around type issues
- Code organization issues: Over-engineering, duplicating existing functionality, breaking existing patterns
- Consistency violations: Inconsistent naming, not following file structure, magic numbers/strings
- Debug artifacts: `print()` statements, unused imports, test code in production
- Pattern violations: Not following existing patterns, breaking conventions, adding features not requested
- Generic & vague code: Empty AI-words ("robust", "seamless", "efficient"), generic variable names

If you encounter any of these patterns:

- Remove them immediately
- Replace with proper patterns from the codebase
- Verify the fix doesn't break existing functionality

## Checklist

- [ ] Read and understood the entire file being edited
- [ ] Checked similar files to understand existing patterns
- [ ] Searched for existing implementations - found similar functionality and leveraged/expanded it
- [ ] Traced dependencies - verified changes won't break other things
- [ ] Matched existing naming conventions exactly
- [ ] Followed existing import style and organization
- [ ] Used existing constants/config instead of magic values
- [ ] ALL tests pass (`uv run test all`)
- [ ] Quality checks pass (`uv run dev all`)
- [ ] Type checking passes (`uv run basedpyright`)
- [ ] No unused imports (`ruff check --select F401`)
- [ ] No commented-out code
- [ ] All public APIs have docstrings (NumPy format)
- [ ] All functions have type hints
- [ ] No `# type: ignore` or `cast(Any, ...)` comments
- [ ] No `print()` statements (use `loguru`)
- [ ] Database operations use controllers via `DatabaseCoordinator`
- [ ] Error handling uses custom exceptions (`TuxError` hierarchy)
- [ ] Only requested changes were made (no scope creep)
- [ ] No unrelated code was modified
- [ ] Established patterns were preserved exactly
- [ ] All API calls verified to exist in actual libraries
- [ ] Verified against usage - read calling code, checked what fields/properties are accessed
- [ ] Adversarial verification - tested edge cases, null/undefined, empty payloads

## See Also

- Related command: `/lint`
- Related command: `/refactor`
- Related command: `/review-existing-diffs`
- Related rule: @core/tech-stack.mdc
- Related rule: @database/controllers.mdc
- Related rule: @database/models.mdc
- Related rule: @modules/commands.mdc
59 changes: 59 additions & 0 deletions .cursor/commands/code-quality/lint.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Lint and Fix Code

## Overview

Run Tux project linters (ruff, basedpyright) and automatically fix issues according to project coding standards.

## Steps

1. **Run Linters**
- Format code: `uv run ruff format .`
- Fix auto-fixable issues: `uv run ruff check --fix .`
- Check types: `uv run basedpyright`
- Run all checks: `uv run dev all`
2. **Identify Issues**
- Ruff linting violations (imports, style, complexity)
- Type errors from basedpyright
- Unused imports and variables
- Missing type hints (`Type | None` not `Optional[Type]`)
- NumPy docstring format violations
3. **Apply Fixes**
- Auto-fix with ruff where possible
- Add type hints with strict typing
- Use `Type | None` convention
- Fix import organization (stdlib → third-party → local)
- Update docstrings to NumPy format
4. **Verify Standards**
- 88 character line length
- snake_case for functions/variables
- PascalCase for classes
- UPPER_CASE for constants
- Absolute imports preferred

## Error Handling

If linting fails:

- Review error messages carefully
- Some issues may require manual fixes
- Type errors may need code changes
- Import organization can be auto-fixed

## Lint Checklist

- [ ] Ran `uv run ruff format .`
- [ ] Ran `uv run ruff check --fix .`
- [ ] Ran `uv run basedpyright`
- [ ] Fixed all type errors
- [ ] Added missing type hints
- [ ] Used `Type | None` convention
- [ ] Organized imports correctly
- [ ] Updated docstrings to NumPy format
- [ ] Verified naming conventions
- [ ] Ran `uv run dev all` successfully

## See Also

- Related command: `/refactor`
- Related command: `/review-existing-diffs`
- Related rule: @core/tech-stack.mdc
58 changes: 58 additions & 0 deletions .cursor/commands/code-quality/refactor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Refactor Code

## Overview

Refactor code to follow Tux project patterns, Discord.py best practices, and Python standards while maintaining functionality.

## Steps

1. **Code Quality Improvements**
- Extract reusable functions following DRY principle
- Eliminate code duplication across cogs
- Improve naming (snake_case, PascalCase, UPPER_CASE)
- Simplify nested async/await patterns
2. **Discord.py Patterns**
- Use hybrid commands (slash + traditional)
- Implement proper command error handlers
- Use embeds from `tux.ui.embeds`
- Follow cog structure from `src/modules/`
3. **Database Patterns**
- Use service layer for business logic
- Use controllers for database operations
- Never access database session directly
- Implement proper transaction handling
4. **Python Best Practices**
- Add strict type hints
- Use NumPy docstring format
- Follow async/await patterns
- Keep files under 1600 lines

## Error Handling

During refactoring:

- Run tests frequently to catch regressions
- Use `uv run test quick` for fast feedback
- Check for breaking changes
- Verify all functionality still works

## Refactor Checklist

- [ ] Extracted reusable functions
- [ ] Eliminated code duplication
- [ ] Improved naming conventions
- [ ] Simplified complex nested logic
- [ ] Used proper Discord.py command patterns
- [ ] Implemented service layer architecture
- [ ] Added strict type hints
- [ ] Updated to NumPy docstrings
- [ ] Verified async/await patterns
- [ ] Kept files under 1600 lines
- [ ] Ran tests to verify functionality

## See Also

- Related command: `/lint`
- Related command: `/write-unit-tests`
- Related rule: @modules/cogs.mdc
- Related rule: @database/controllers.mdc
Loading
Loading