@tenantegroup/ai-rules-mcp 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/INSTALLATION.md +52 -0
  2. package/README.md +57 -0
  3. package/USAGE.md +46 -0
  4. package/package.json +57 -0
  5. package/rules/cloudflare/api-services.md +80 -0
  6. package/rules/cloudflare/cicd-deployment.md +56 -0
  7. package/rules/cloudflare/database-orm.md +28 -0
  8. package/rules/cloudflare/edge-parity.md +24 -0
  9. package/rules/cloudflare/kv-usage.md +31 -0
  10. package/rules/cloudflare/logging-observability.md +66 -0
  11. package/rules/cloudflare/performance.md +44 -0
  12. package/rules/cloudflare/realtime-background.md +58 -0
  13. package/rules/cloudflare/security.md +162 -0
  14. package/rules/cloudflare/seeding.md +27 -0
  15. package/rules/cloudflare/workflows.md +593 -0
  16. package/rules/dotnet/api.md +26 -0
  17. package/rules/dotnet/architecture.md +27 -0
  18. package/rules/dotnet/cli.md +26 -0
  19. package/rules/dotnet/configuration.md +26 -0
  20. package/rules/dotnet/logging.md +25 -0
  21. package/rules/dotnet/maui.md +26 -0
  22. package/rules/dotnet/mvvm.md +26 -0
  23. package/rules/dotnet/packaging.md +24 -0
  24. package/rules/dotnet/project-structure.md +26 -0
  25. package/rules/dotnet/sqlite.md +29 -0
  26. package/rules/dotnet/testing.md +24 -0
  27. package/rules/flutter/api.md +29 -0
  28. package/rules/flutter/architecture.md +34 -0
  29. package/rules/flutter/auth.md +27 -0
  30. package/rules/flutter/configuration.md +24 -0
  31. package/rules/flutter/database.md +30 -0
  32. package/rules/flutter/logging.md +27 -0
  33. package/rules/flutter/navigation.md +28 -0
  34. package/rules/flutter/offline-sync.md +26 -0
  35. package/rules/flutter/platform.md +30 -0
  36. package/rules/flutter/project-structure.md +32 -0
  37. package/rules/flutter/riverpod.md +32 -0
  38. package/rules/flutter/testing.md +31 -0
  39. package/rules/nuxt/architecture-principles.md +31 -0
  40. package/rules/nuxt/authentication.md +35 -0
  41. package/rules/nuxt/code-quality.md +71 -0
  42. package/rules/nuxt/configuration.md +31 -0
  43. package/rules/nuxt/core-directives.md +12 -0
  44. package/rules/nuxt/project-initialization.md +53 -0
  45. package/rules/nuxt/project-structure.md +44 -0
  46. package/rules/nuxt/testing.md +48 -0
  47. package/src/index.js +757 -0
  48. package/templates/cloudflare/compile-context.js +43 -0
  49. package/templates/cloudflare/hooks/post-checkout +5 -0
  50. package/templates/cloudflare/hooks/pre-commit +14 -0
  51. package/templates/cloudflare/install-hooks.js +34 -0
  52. package/templates/cloudflare/validate-code.js +57 -0
  53. package/templates/dotnet/compile-context.js +43 -0
  54. package/templates/dotnet/hooks/post-checkout +5 -0
  55. package/templates/dotnet/hooks/pre-commit +14 -0
  56. package/templates/dotnet/install-hooks.js +34 -0
  57. package/templates/dotnet/validate-code.js +84 -0
  58. package/templates/flutter/compile-context.js +43 -0
  59. package/templates/flutter/hooks/post-checkout +5 -0
  60. package/templates/flutter/hooks/pre-commit +14 -0
  61. package/templates/flutter/install-hooks.js +34 -0
  62. package/templates/flutter/validate-code.js +64 -0
  63. package/templates/nuxt/compile-context.js +43 -0
  64. package/templates/nuxt/hooks/post-checkout +5 -0
  65. package/templates/nuxt/hooks/pre-commit +14 -0
  66. package/templates/nuxt/install-hooks.js +34 -0
  67. package/templates/nuxt/validate-code.js +57 -0
@@ -0,0 +1,52 @@
1
+ # Installation Guide: `@tenantegroup/ai-rules-mcp`
2
+
3
+ This guide explains how to hook the unified AI Rules MCP server into various AI assistants and editors.
4
+
5
+ ---
6
+
7
+ ## 1. Prerequisites
8
+ Ensure you have Node.js (version 18 or higher) installed on your system.
9
+
10
+ Install the package globally:
11
+ ```bash
12
+ npm install -g @tenantegroup/ai-rules-mcp
13
+ ```
14
+
15
+ ---
16
+
17
+ ## 2. Editor & Client Configuration
18
+
19
+ ### Claude Desktop (macOS & Windows)
20
+ 1. Open the Claude config file:
21
+ * **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
22
+ * **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
23
+ 2. Add the following entry:
24
+ ```json
25
+ {
26
+ "mcpServers": {
27
+ "ai-rules": {
28
+ "command": "ai-rules-mcp"
29
+ }
30
+ }
31
+ }
32
+ ```
33
+ 3. Restart Claude Desktop.
34
+
35
+ ### Cursor / VS Code (with Roo Code or Cline)
36
+ If you are using extension engines supporting MCP in VS Code:
37
+ 1. Open the extension's MCP Settings panel.
38
+ 2. Click **Add New MCP Server**.
39
+ 3. Set parameters:
40
+ * **Name**: `ai-rules`
41
+ * **Type**: `command`
42
+ * **Command**: `ai-rules-mcp`
43
+ 4. Save and restart the extension.
44
+
45
+ ---
46
+
47
+ ## 3. Verifying Installation
48
+ In your chat, ask the assistant:
49
+ * *"List all rules available in the AI Rules MCP server"*
50
+ * *"Get the Cloudflare workflows rule"*
51
+
52
+ The assistant should trigger a tool call to the server and display the returned Markdown content.
package/README.md ADDED
@@ -0,0 +1,57 @@
1
+ # Unified AI Rules MCP Server (`@tenantegroup/ai-rules-mcp`)
2
+
3
+ Model Context Protocol (MCP) server providing structured AI coding rules for **Cloudflare Backend**, **Nuxt Frontend**, **Flutter Client**, and **.NET MAUI Client** stacks.
4
+
5
+ It dynamically selects relevant rules based on task descriptions, file types, and keywords, achieving a **~75% token reduction** compared to loading all rules at once.
6
+
7
+ ---
8
+
9
+ ## ⚡ Key Features
10
+
11
+ 1. **Smart Context Filtering**: Excludes dotNET rules during Flutter sessions and vice-versa, avoiding AI confusion and conserving token limits.
12
+ 2. **Unified Installation**: One global package to install and maintain instead of multiple repository setups.
13
+ 3. **Smart Scaffolder**: Run `install_rules_to_project` in any workspace. It auto-detects whether the project is Flutter, Nuxt, dotNET, or Cloudflare, and scaffolds the exact rules, context compilation, and pre-commit Git validators needed for that technology.
14
+
15
+ ---
16
+
17
+ ## 🛠️ Tech Stacks Covered
18
+
19
+ * **Cloudflare Backend**: Workers runtime edge parity, Drizzle ORM, D1 SQLite database, Workflows (durable sagas), KV storage, R2 bucket storage, and Durable Objects.
20
+ * **Nuxt Frontend**: Nuxt 4 directory structures, Pinia reactive state, components routing, and API integration client-side.
21
+ * **Flutter Client**: Riverpod state management, GoRouter routing, Retrofit client API integration, and Drift SQLite persistent database.
22
+ * **dotNET Client**: .NET MAUI UI shell, XAML layouts, MVVM pattern via CommunityToolkit, Refit strongly-typed HTTP, and sqlite-net.
23
+
24
+ ---
25
+
26
+ ## 🚀 Quick Start
27
+
28
+ ### 1. Global Installation
29
+ Install the unified package globally:
30
+ ```bash
31
+ npm install -g @tenantegroup/ai-rules-mcp
32
+ ```
33
+
34
+ ### 2. Configure Claude Desktop
35
+ Edit your Claude Desktop configuration (e.g. `%APPDATA%\Claude\claude_desktop_config.json` on Windows or `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS):
36
+
37
+ ```json
38
+ {
39
+ "mcpServers": {
40
+ "ai-rules": {
41
+ "command": "ai-rules-mcp"
42
+ }
43
+ }
44
+ }
45
+ ```
46
+
47
+ Restart Claude Desktop, and the server will be active.
48
+
49
+ ---
50
+
51
+ ## 📖 Available Tools
52
+
53
+ * `get_relevant_rules(task_description, file_types, keywords)`: Automatically detects target stacks and returns relevant directives.
54
+ * `get_rule_by_name(rule_name)`: Returns a specific rule (e.g., `flutter/riverpod` or `cloudflare/workflows`).
55
+ * `search_rule_content(query)`: Performs a regex search across the contents of all rule files.
56
+ * `list_all_rules()`: Lists available rules grouped by technology stack.
57
+ * `install_rules_to_project(target_dir, stack)`: Scaffolds the `.ai/rules/` directory and stack-specific Git validators (`validate-code.js`) into the target repository.
package/USAGE.md ADDED
@@ -0,0 +1,46 @@
1
+ # Usage Guide: `@tenantegroup/ai-rules-mcp`
2
+
3
+ The unified AI Rules MCP server can be used both directly by AI assistants during development and as a command-line tool to initialize new projects.
4
+
5
+ ---
6
+
7
+ ## 1. Interaction Guidelines (For AI Assistants)
8
+
9
+ The assistant should call the tools automatically when you describe tasks. However, you can guide the assistant explicitly:
10
+
11
+ * **Task-Based Rules**: Ask the AI to:
12
+ * *"Fetch the relevant rules for adding a table to my Drift database in Flutter."*
13
+ * *"Get rules for deploying a Worker using GitHub Actions."*
14
+ * **Direct Rule Lookup**: Ask:
15
+ * *"Show the C# MVVM standards."*
16
+ * *"Load the Cloudflare Edge Parity rules."*
17
+
18
+ The assistant uses the `get_relevant_rules` tool which filters files to minimize token footprint.
19
+
20
+ ---
21
+
22
+ ## 2. Setting Up a Local Project (For Developers)
23
+
24
+ To configure static testing, compilation, and git hooks inside a repository, the assistant or developer can call `install_rules_to_project`.
25
+
26
+ ### Scaffolding via Claude/AI:
27
+ Just type:
28
+ > *"Install the AI rules to this project"* (or specify a path: *"Install the AI rules to /path/to/my-project"*).
29
+
30
+ The tool will:
31
+ 1. Scan your project folder.
32
+ 2. Auto-detect if it's a **Flutter**, **dotNET**, **Nuxt**, or **Cloudflare** workspace.
33
+ 3. Create `.ai/rules/` and copy only the rule files for that stack.
34
+ 4. Copy validation tools (`validate-code.js`) if available.
35
+
36
+ ### Activate Local Git Hooks & Context (Nuxt/Cloudflare stacks):
37
+ If you initialized a Nuxt/Cloudflare project:
38
+ 1. Run the hook installer to prevent non-compliant commits:
39
+ ```bash
40
+ node .ai/scripts/install-hooks.js
41
+ ```
42
+ 2. Compile rule sets into `.cursorrules`, `CLAUDE.md`, and `GEMINI.md`:
43
+ ```bash
44
+ node .ai/scripts/compile-context.js
45
+ ```
46
+ This ensures that even local offline models read rules instantly.
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@tenantegroup/ai-rules-mcp",
3
+ "version": "1.0.0",
4
+ "description": "Unified MCP server providing AI coding rules for Cloudflare Backend, Nuxt Frontend, Flutter Client, and dotNET MAUI stacks with smart context filtering",
5
+ "main": "src/index.js",
6
+ "type": "module",
7
+ "bin": {
8
+ "ai-rules-mcp": "src/index.js"
9
+ },
10
+ "scripts": {
11
+ "start": "node src/index.js",
12
+ "test": "echo \"Error: no test specified\" && exit 1"
13
+ },
14
+ "keywords": [
15
+ "mcp",
16
+ "ai",
17
+ "coding-rules",
18
+ "model-context-protocol",
19
+ "cloudflare",
20
+ "workers",
21
+ "d1",
22
+ "drizzle",
23
+ "workflows",
24
+ "nuxt",
25
+ "vue",
26
+ "flutter",
27
+ "dart",
28
+ "riverpod",
29
+ "drift",
30
+ "dotnet",
31
+ "csharp",
32
+ "maui",
33
+ "mvvm",
34
+ "sqlite",
35
+ "refit",
36
+ "claude",
37
+ "copilot",
38
+ "gemini"
39
+ ],
40
+ "author": "",
41
+ "license": "MIT",
42
+ "files": [
43
+ "src/",
44
+ "rules/",
45
+ "templates/",
46
+ "README.md",
47
+ "INSTALLATION.md",
48
+ "USAGE.md"
49
+ ],
50
+ "engines": {
51
+ "node": ">=18.0.0"
52
+ },
53
+ "dependencies": {
54
+ "@modelcontextprotocol/sdk": "^1.27.1",
55
+ "zod": "^4.3.6"
56
+ }
57
+ }
@@ -0,0 +1,80 @@
1
+ # API-Only Service Standards
2
+
3
+ ## Framework Standard
4
+ - Use Nuxt (Nitro) deployed to Cloudflare Workers for all API-only backend services
5
+ - Do NOT introduce additional backend frameworks (e.g., Hono) without documented technical limitation
6
+ - Treat Nuxt as a structured server framework (UI layer not required)
7
+
8
+ ## API Design Principles
9
+ All API services must:
10
+ - Use REST architecture with mandatory versioning (`/api/v1/...`)
11
+ - Enforce Zod validation on all inputs
12
+ - Implement structured logging with request IDs
13
+ - Use centralized error handling
14
+ - Apply API key authentication as minimum standard
15
+ - Implement rate limiting where appropriate
16
+ - Include audit logging for sensitive operations
17
+ - Follow D1 migration and testing standards
18
+
19
+ ## Project Structure for API-Only Services
20
+ Organize API routes by version:
21
+ ```
22
+ server/
23
+ api/
24
+ v1/
25
+ users.get.ts
26
+ users.post.ts
27
+ tasks.get.ts
28
+ middleware/
29
+ services/
30
+ utils/
31
+ ```
32
+
33
+ ## API Route Pattern
34
+ Every endpoint must:
35
+ - Wrap handler in centralized error handling
36
+ - Use structured logger
37
+ - Validate input using Zod schemas
38
+ - Return consistent JSON structure
39
+ - Include appropriate HTTP status codes
40
+
41
+ ## Versioning Strategy
42
+ - Use URL path versioning: `/api/v1/`, `/api/v2/`
43
+ - Never break existing API versions
44
+ - Maintain backward compatibility when possible
45
+ - Deprecate old versions with clear timeline
46
+
47
+ ## Authentication for APIs
48
+ Choose based on consumer type:
49
+ - **Internal Services**: Mutual TLS or API key authentication
50
+ - **Mobile Apps**: JWT access tokens + refresh tokens
51
+ - **Third-Party**: API key + secret with rate limiting
52
+ - **Public APIs**: OAuth 2.0 where appropriate
53
+
54
+ ## Response Format Standard
55
+ Return consistent JSON structure:
56
+ ```json
57
+ {
58
+ "success": true,
59
+ "data": {...},
60
+ "error": null
61
+ }
62
+ ```
63
+
64
+ Or for errors:
65
+ ```json
66
+ {
67
+ "success": false,
68
+ "data": null,
69
+ "error": {
70
+ "code": "ERROR_CODE",
71
+ "message": "User-friendly message"
72
+ }
73
+ }
74
+ ```
75
+
76
+ ## Future-Proofing
77
+ Structure projects so they can evolve into fullstack Nuxt applications without architectural rewrites.
78
+
79
+ ## Consistency Rule
80
+ Nuxt + Cloudflare is the backend platform. Framework consistency is mandatory.
@@ -0,0 +1,56 @@
1
+ # CI/CD & Deployment Standards
2
+
3
+ ## Branch Model
4
+ Use Git flow with these branches:
5
+ - `main` → production environment
6
+ - `staging` → staging environment
7
+ - `feature/*` → pull requests only (no direct deployment)
8
+
9
+ ## Deployment Rules
10
+ - Deploy to production only from `main` branch
11
+ - Deploy to staging only from `staging` branch
12
+ - Execute all migrations before production release
13
+ - Run smoke tests after deployment
14
+ - Require pull request approval before merging to `main`
15
+
16
+ ## CI Pipeline Requirements
17
+ Every project must have GitHub Actions workflow including:
18
+ 1. **Install**: Install dependencies
19
+ 2. **Build**: Build application with Cloudflare preset
20
+ 3. **Test**: Run full test suite
21
+ 4. **Deploy**: Deploy via Wrangler to appropriate environment
22
+
23
+ ## Pre-Deployment Checklist
24
+ Before every production deployment:
25
+ - [ ] All tests passing
26
+ - [ ] Migration review completed
27
+ - [ ] Staging deployment verified
28
+ - [ ] Database backups confirmed (if applicable)
29
+ - [ ] Rollback plan documented
30
+
31
+ ## Deployment Process
32
+ 1. Merge approved PR to `main` or `staging`
33
+ 2. CI pipeline runs automatically
34
+ 3. Migrations execute before code deployment
35
+ 4. Application deploys via Wrangler
36
+ 5. Smoke test endpoint validates deployment
37
+ 6. Monitor logs for errors
38
+
39
+ ## Smoke Test Requirements
40
+ - Create health check endpoint at `/api/health`
41
+ - Verify database connectivity
42
+ - Verify critical bindings (D1, KV, etc.)
43
+ - Return 200 OK when healthy
44
+ - Return 503 when unhealthy
45
+
46
+ ## Environment-Specific Configuration
47
+ - Use Wrangler environment blocks in `wrangler.toml`
48
+ - Configure separate D1 databases per environment
49
+ - Use environment-specific secrets
50
+ - Test environment parity locally before deployment
51
+
52
+ ## Rollback Strategy
53
+ - Tag releases in Git for easy rollback
54
+ - Document rollback procedure in README
55
+ - Keep previous version deployable
56
+ - Test rollback process in staging
@@ -0,0 +1,28 @@
1
+ # Database & ORM Standards
2
+
3
+ ## Database Strategy
4
+ - Use D1 (SQLite) as default for all projects
5
+ - Maintain one database per environment
6
+ - Apply schema-first thinking to database design
7
+ - Never use KV as primary relational storage (KV is cache only)
8
+
9
+ ## Drizzle ORM Pattern
10
+ - Maintain one central schema file at `/server/db/schema.ts`
11
+ - Define all tables clearly with explicit typing
12
+ - Declare relations explicitly
13
+ - Encapsulate all queries within services
14
+ - Avoid raw SQL unless absolutely necessary
15
+ - Inject database instances into service constructors
16
+
17
+ ## Migration Rules
18
+ - Generate a new migration for every schema change using `drizzle-kit generate`
19
+ - Never modify migrations after they have been applied
20
+ - Commit all migrations to the repository
21
+ - Review production migrations before deployment
22
+ - Apply migrations using `drizzle-kit migrate`
23
+
24
+ ## Query Guidelines
25
+ - Keep all queries encapsulated within service methods
26
+ - Use Drizzle's query builder for type safety
27
+ - Avoid N+1 query patterns
28
+ - Index frequently queried columns
@@ -0,0 +1,24 @@
1
+ # Cloudflare Edge Parity
2
+
3
+ ## Runtime Requirements
4
+ - Design all code for Cloudflare Workers runtime, not Node.js
5
+ - Use Web Standard APIs only (Fetch, Web Crypto, Service Worker model)
6
+ - Never use Node core modules: `fs`, `path`, `net`, `process`, `crypto` (Node version)
7
+ - Ensure local development, CI, and production behave identically
8
+
9
+ ## Required Tooling
10
+ - Use `wrangler dev` for local development (not `nuxt dev` alone)
11
+ - Apply local D1 migrations before any production deployment
12
+ - Declare all bindings (D1, KV, R2, Queues, Durable Objects) in `wrangler.toml`
13
+ - Test bindings locally before deployment
14
+ - Use Nitro Cloudflare preset for all Nuxt projects
15
+ - Access environment variables via Worker bindings, never `process.env`
16
+
17
+ ## Development Workflow
18
+ - Run projects locally using `wrangler dev`
19
+ - Validate all features against local Worker runtime before deployment
20
+ - Pass all E2E tests against `http://localhost:8787`
21
+ - Run full parity pipeline in CI
22
+
23
+ ## Critical Rule
24
+ Deployment must never be the first time Cloudflare runtime behavior is validated.
@@ -0,0 +1,31 @@
1
+ # KV Usage Policy
2
+
3
+ ## Core Principle
4
+ KV is an acceleration layer, not a database.
5
+
6
+ ## Appropriate KV Use Cases
7
+ Use KV for:
8
+ - Caching expensive database reads
9
+ - Rate limiting counters
10
+ - Feature flags
11
+ - Session caching (with D1 as source of truth)
12
+ - Temporary data with TTL requirements
13
+
14
+ ## KV Restrictions
15
+ Never use KV for:
16
+ - Primary relational data storage
17
+ - Critical data without D1 backup
18
+ - Complex querying or joins
19
+ - Transactional operations
20
+ - Data requiring strong consistency guarantees
21
+
22
+ ## Data Hierarchy
23
+ - D1 = source of truth
24
+ - KV = performance enhancement layer
25
+
26
+ ## Implementation Guidelines
27
+ - Always write to D1 first, then cache in KV
28
+ - Set appropriate TTL values for cached data
29
+ - Implement cache invalidation strategies
30
+ - Handle KV misses gracefully by falling back to D1
31
+ - Document what data is cached and why
@@ -0,0 +1,66 @@
1
+ # Logging & Observability
2
+
3
+ ## Core Logging Principles
4
+ - All logs must be structured JSON format
5
+ - Every request must have a unique `requestId`
6
+ - Never log secrets or sensitive credentials
7
+ - Disable debug logs in production
8
+ - Maintain logging consistency across all project components
9
+
10
+ ## Required Log Fields
11
+ Include in every log entry:
12
+ - `level` (debug, info, warn, error, fatal)
13
+ - `event` (machine-readable event name)
14
+ - `timestamp` (ISO 8601 format)
15
+ - `requestId` (unique per request)
16
+
17
+ Optional but recommended:
18
+ - `userId`
19
+ - `organizationId`
20
+ - `durationMs`
21
+ - `metadata` (context-specific data)
22
+
23
+ ## Log Levels Standard
24
+ Use these levels consistently:
25
+ - **debug**: Development diagnostics only (disabled in production)
26
+ - **info**: Normal business events and operations
27
+ - **warn**: Recoverable issues requiring attention
28
+ - **error**: Operational failures
29
+ - **fatal**: System-level crash or unrecoverable state
30
+
31
+ ## Where Logging Must Occur
32
+ Implement logging at:
33
+ - **Middleware**: Request start, response status, duration
34
+ - **Services**: Major business events (create, update, delete)
35
+ - **Database**: Slow queries, connection issues
36
+ - **Background Jobs**: Job start, completion, failure
37
+ - **Authentication**: Login attempts, failures, logouts
38
+
39
+ ## Request ID Implementation
40
+ - Generate unique `requestId` using `crypto.randomUUID()` in middleware
41
+ - Attach `requestId` to event context
42
+ - Include `requestId` in all downstream logs
43
+ - Use `requestId` to trace requests across services
44
+
45
+ ## Centralized Logger
46
+ - Create single logger utility at `/server/utils/logger.ts`
47
+ - Use logger utility consistently across entire application
48
+ - Never use `console.log` directly in application code
49
+
50
+ ## Production Observability Minimum
51
+ Implement before production launch:
52
+ - Request logging with request IDs
53
+ - Error boundaries with proper logging
54
+ - Health check endpoint for monitoring
55
+ - Structured log output for aggregation
56
+
57
+ ## Scaling Observability
58
+ Add as system matures:
59
+ - External log aggregation service
60
+ - Error tracking service (e.g., Sentry)
61
+ - Performance monitoring
62
+ - Alerting on critical errors
63
+ - Dashboard for operational metrics
64
+
65
+ ## Critical Rule
66
+ If production fails, diagnosis must be possible through logs alone.
@@ -0,0 +1,44 @@
1
+ # Performance Standards
2
+
3
+ ## Core Principle
4
+ Measure first. Optimize second.
5
+
6
+ ## Pre-Optimization Checklist
7
+ Before adding infrastructure, verify you have:
8
+ - [ ] Indexed all frequently queried database columns
9
+ - [ ] Eliminated N+1 query patterns
10
+ - [ ] Cached heavy reads in KV where appropriate
11
+ - [ ] Minimized JSON payload sizes
12
+ - [ ] Implemented lazy-loading for heavy frontend components
13
+ - [ ] Measured actual performance bottlenecks
14
+
15
+ ## Scaling Path (In Order)
16
+ Add optimizations incrementally as needed:
17
+ 1. **Phase 1**: Add KV caching layer for read-heavy operations
18
+ 2. **Phase 2**: Implement rate limiting to protect resources
19
+ 3. **Phase 3**: Introduce Queues for background processing
20
+ 4. **Phase 4**: Harden RBAC and add granular permissions
21
+ 5. **Phase 5**: Add advanced monitoring and alerting
22
+
23
+ ## Database Performance
24
+ - Index columns used in WHERE clauses
25
+ - Index columns used in JOIN conditions
26
+ - Index columns used for sorting
27
+ - Avoid SELECT * queries; request only needed columns
28
+ - Use database query analysis to identify slow queries
29
+
30
+ ## Caching Strategy
31
+ - Cache expensive computations in KV
32
+ - Set appropriate TTL values
33
+ - Implement cache invalidation on writes
34
+ - Monitor cache hit rates
35
+ - Document what is cached and why
36
+
37
+ ## Frontend Performance
38
+ - Lazy-load components not needed on initial render
39
+ - Minimize bundle size
40
+ - Use code splitting where appropriate
41
+ - Optimize images and assets
42
+
43
+ ## Critical Rule
44
+ Never prematurely optimize. Optimize only when measurements justify the effort.
@@ -0,0 +1,58 @@
1
+ # Realtime & Background Processing
2
+
3
+ ## Durable Objects
4
+
5
+ Use Durable Objects only when:
6
+ - Coordinated shared state is required across multiple clients
7
+ - Building realtime collaboration features
8
+ - Implementing chat systems or presence features
9
+ - Consistent state management is needed beyond simple KV
10
+
11
+ Do NOT use for:
12
+ - Simple async tasks (use Queues instead)
13
+ - General caching (use KV instead)
14
+ - Standard CRUD operations (use D1 instead)
15
+ - Multi-step orchestration (use Workflows instead)
16
+
17
+ ## Queues
18
+
19
+ Use Cloudflare Queues for:
20
+ - Asynchronous email processing
21
+ - Webhook delivery and retry logic
22
+ - Background job processing
23
+ - Decoupled async workloads
24
+ - Tasks that can tolerate eventual consistency
25
+
26
+ Do NOT use for:
27
+ - Multi-step transactions requiring state persistence (use Workflows instead)
28
+ - Operations requiring saga-pattern rollbacks (use Workflows instead)
29
+ - Long-running operations that exceed ~15 minute execution time (use Workflows instead)
30
+
31
+ Queue Implementation Rules:
32
+ - Keep queue handlers idempotent
33
+ - Implement proper error handling and retry logic
34
+ - Log queue processing for observability
35
+ - Monitor queue depth and processing times
36
+
37
+ ## Push Notifications
38
+ - Handle push notifications via external services (FCM for Android, APNs for iOS)
39
+ - Do NOT implement custom push infrastructure
40
+ - Use Queues to process and batch notification sends
41
+
42
+ ## Decision Tree: Workflows vs Queues vs Durable Objects
43
+
44
+ | Question | Answer | Use |
45
+ |----------|--------|-----|
46
+ | Need to orchestrate multiple external systems? | Yes | **Workflows** |
47
+ | Need to coordinate real-time state across clients? | Yes | **Durable Objects** |
48
+ | Need simple fire-and-forget async tasks? | Yes | **Queues** |
49
+ | Need saga-pattern rollbacks on failure? | Yes | **Workflows** |
50
+ | Need state persistence across pauses? | Yes | **Workflows** |
51
+ | Need to wait for external events/approvals? | Yes | **Workflows** |
52
+ | Need to coordinate in-memory state for 1-2 clients? | Yes | **Durable Objects** |
53
+ | Need to process batches of simple tasks? | Yes | **Queues** |
54
+
55
+ **For comprehensive guidance on Workflows** (orchestration, saga rollbacks, idempotency, state management), see **09-workflows.md**.
56
+
57
+ ## General Guideline
58
+ Start simple. Add Durable Objects, Queues, or Workflows only when clear requirements justify them.