ai-ops-compiler 0.1.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 (42) hide show
  1. package/README.md +124 -0
  2. package/data/presets.yaml +52 -0
  3. package/data/references/README.md +34 -0
  4. package/data/references/claude-code/best-practices/context-optimization.md +114 -0
  5. package/data/references/claude-code/hooks.md +65 -0
  6. package/data/references/claude-code/rules.md +63 -0
  7. package/data/references/claude-code/skills.md +72 -0
  8. package/data/references/codex/best-practices/context-optimization.md +120 -0
  9. package/data/references/codex/rules.md +53 -0
  10. package/data/references/codex/skills.md +68 -0
  11. package/data/references/gemini-cli/best-practices/context-optimization.md +54 -0
  12. package/data/references/gemini-cli/custom-commands.md +60 -0
  13. package/data/references/gemini-cli/hooks.md +61 -0
  14. package/data/references/gemini-cli/rules.md +55 -0
  15. package/data/references/gemini-cli/skills.md +65 -0
  16. package/data/rules/ai-llm-python.yaml +35 -0
  17. package/data/rules/code-philosophy.yaml +30 -0
  18. package/data/rules/communication.yaml +11 -0
  19. package/data/rules/data-pipeline-python.yaml +34 -0
  20. package/data/rules/engineering-standards.yaml +40 -0
  21. package/data/rules/fastapi.yaml +37 -0
  22. package/data/rules/flutter.yaml +40 -0
  23. package/data/rules/graphql.yaml +34 -0
  24. package/data/rules/libs-backend-python.yaml +36 -0
  25. package/data/rules/libs-backend-ts.yaml +43 -0
  26. package/data/rules/libs-frontend-app.yaml +42 -0
  27. package/data/rules/libs-frontend-web.yaml +49 -0
  28. package/data/rules/naming-convention.yaml +10 -0
  29. package/data/rules/nestjs-graphql.yaml +31 -0
  30. package/data/rules/nestjs.yaml +26 -0
  31. package/data/rules/nextjs.yaml +34 -0
  32. package/data/rules/prisma-postgresql.yaml +30 -0
  33. package/data/rules/python.yaml +31 -0
  34. package/data/rules/react-typescript.yaml +11 -0
  35. package/data/rules/role-persona.yaml +14 -0
  36. package/data/rules/shadcn-ui.yaml +36 -0
  37. package/data/rules/sqlalchemy.yaml +32 -0
  38. package/data/rules/typescript.yaml +22 -0
  39. package/dist/index.d.ts +339 -0
  40. package/dist/index.js +379 -0
  41. package/dist/index.js.map +1 -0
  42. package/package.json +38 -0
@@ -0,0 +1,40 @@
1
+ id: flutter
2
+ category: framework
3
+ tags:
4
+ - dart
5
+ - flutter
6
+ - riverpod
7
+ - mobile
8
+ priority: 30
9
+ content:
10
+ constraints:
11
+ - 'DO NOT use `dynamic` type. Use `Object` or sealed class + pattern matching instead.'
12
+ - 'DO NOT place business logic inside Widget `build()`. Widgets are UI declarations only; move logic to Notifier/Controller or `*.logic.dart` pure functions.'
13
+ - "DO NOT use StatefulWidget for shared state that outlives a single widget's lifecycle. Use Riverpod provider instead."
14
+ - 'DO NOT use GlobalKey to access widget state. Pass data via provider or callback props to preserve tree encapsulation.'
15
+ - 'DO NOT use mutable class fields. All fields must be `final`; use freezed/copyWith for data class updates.'
16
+ - 'DO NOT block the UI thread with heavy synchronous operations (e.g., large JSON parsing, image processing). Use `compute` or a dedicated Isolate.'
17
+ guidelines:
18
+ - 'Use Riverpod with code generation (`@riverpod` annotation). Co-locate providers with the feature directory that consumes them.'
19
+ - 'Adopt feature-first directory structure: `lib/features/<feature>/{view,model,provider,logic}`. Shared code goes in `lib/core/`.'
20
+ - 'Use sealed class + switch expression for union types (Dart 3 pattern). Apply to AsyncValue and Result patterns.'
21
+ - "Prefer `const` constructors on all widgets and data classes to enable Flutter's rebuild optimization."
22
+ - 'Use GoRouter for declarative routing and deep-link support. Avoid imperative `Navigator.push()`/`pop()`.'
23
+ - 'Use `freezed` (`@freezed` annotation) for immutable data classes to auto-generate copyWith, equality, and JSON serialization. Never implement `==`/`hashCode` manually.'
24
+ - 'Write widget tests with `pumpWidget` + `ProviderScope.overrides` for DI mocking. Test pure logic functions with plain unit tests.'
25
+ - 'Use `RepaintBoundary` to isolate expensive subtree repaints. Profile with Flutter DevTools before optimizing; avoid premature optimization.'
26
+ - 'Handle async states explicitly using Riverpod AsyncValue or a Result pattern (loading / success / failure). Set a global error boundary to prevent unhandled exceptions from reaching the UI.'
27
+ - 'Abstract all external data access behind a Repository interface. Providers must never call APIs or databases directly; they receive a Repository implementation via Riverpod DI.'
28
+ decision_table:
29
+ - when: 'State is ephemeral and scoped to a single widget (e.g., form field focus, animation toggle)'
30
+ then: 'Use StatefulWidget or flutter_hooks useState'
31
+ avoid: 'Creating a Riverpod provider for trivial local UI state'
32
+ - when: "State is shared across widgets or must persist beyond a single widget's lifecycle"
33
+ then: 'Use Riverpod Notifier or AsyncNotifier'
34
+ avoid: 'StatefulWidget with callback prop drilling or InheritedWidget'
35
+ - when: 'A data class requires equality, copyWith, or JSON serialization'
36
+ then: 'Annotate with `@freezed` and run build_runner'
37
+ avoid: 'Manually implementing `==`, `hashCode`, or `copyWith`'
38
+ - when: 'Navigating between screens or handling deep links'
39
+ then: 'Declare routes with GoRouter configuration'
40
+ avoid: 'Imperative Navigator.push() / Navigator.pop()'
@@ -0,0 +1,34 @@
1
+ id: graphql
2
+ category: api
3
+ tags:
4
+ - graphql
5
+ - api
6
+ - schema-design
7
+ priority: 48
8
+ content:
9
+ constraints:
10
+ - 'DO NOT rely on implicit nullability defaults. Every field MUST declare nullability explicitly — non-null (!) is the default intent; nullable fields are intentional design decisions (e.g., optional profile picture). Implicit nullability causes mismatches between schema and client expectations.'
11
+ - 'DO NOT perform side effects (data mutations) in Query resolvers. Reads belong in Query, writes belong in Mutation — strict separation ensures idempotent caching, safe retry behavior, and predictable client behavior.'
12
+ - 'DO NOT use a generic `Error` type as a return value. Define domain-specific union error types per operation (e.g., `union CreateUserResult = User | EmailTakenError | ValidationError`). Generic errors give clients no actionable structure for error handling.'
13
+ - 'DO NOT return unbounded lists. Every collection field MUST apply pagination (`first`/`after` for cursor-based or `limit`/`offset` for offset-based). Unbounded lists are a DoS vector and cause memory exhaustion at scale.'
14
+ - 'DO NOT expose internal implementation details in enum value names. Use SCREAMING_SNAKE_CASE semantic names (e.g., `PENDING`, `IN_PROGRESS`) — never leak DB column names, internal state machine names, or numeric codes that require server-side knowledge to interpret.'
15
+ guidelines:
16
+ - 'Prefer cursor-based pagination (`first`/`after`) using UUID v7 PKs as the cursor — eliminates offset drift on live data and supports infinite scroll reliably. A minimal connection shape `{ nodes: [T!]!, pageInfo: { hasNextPage: Boolean!, endCursor: String } }` is sufficient; full Relay Connection spec (`edges/node`) is optional.'
17
+ - 'Design mutation arguments as a single `input` object: `mutation CreateUser($input: CreateUserInput!) { createUser(input: $input) { ... } }`. Never spread individual scalars as top-level arguments — a single input type is versionable and tooling-friendly.'
18
+ - 'Return a Payload type from every mutation: `type CreateUserPayload { user: User, userErrors: [UserError!]! }`. Return HTTP 200 with application-level errors in `userErrors` rather than using top-level GraphQL errors, which are harder for clients to branch on.'
19
+ - 'Solve N+1 with DataLoader. Resolvers MUST NOT issue DB queries directly — delegate to a batch loader keyed by parent IDs. This is mandatory for any `@ResolveField`-equivalent that loads related data.'
20
+ - 'Follow schema naming conventions: `PascalCase` for types and enums, `camelCase` for fields and arguments, `SCREAMING_SNAKE_CASE` for enum values. Deviations break code generation tools (`@graphql-codegen`).'
21
+ - 'Mark deprecated fields with `@deprecated(reason: "Use newField instead. Removal planned in v3.")` rather than deleting them immediately. Verify client migration before removing in the next major version.'
22
+ decision_table:
23
+ - when: 'A field returns a collection'
24
+ then: 'Use cursor-based pagination (`first`/`after`, UUID v7 PK as cursor) — stable under concurrent writes, safe for infinite scroll. Offset pagination (`limit`/`offset`) is acceptable for admin tables with bounded, slow-changing data.'
25
+ avoid: 'Unbounded `[Node!]!` return — no limit means memory exhaustion and DoS risk at scale'
26
+ - when: 'A mutation needs to communicate failure to the client'
27
+ then: 'Return a Payload union type (`User | ValidationError`) and populate `userErrors: [UserError!]!` — clients can switch on `__typename` and handle errors as data'
28
+ avoid: 'Throwing top-level GraphQL errors for expected business failures — clients must catch exceptions instead of branching on typed data'
29
+ - when: 'A schema field needs to be removed or renamed'
30
+ then: 'Add `@deprecated(reason: "...")` first, confirm all clients have migrated, then remove in the next major schema version'
31
+ avoid: 'Removing a field immediately without deprecation — causes runtime errors in deployed clients that have not yet updated their queries'
32
+ - when: 'A query needs complex filtering or sorting'
33
+ then: 'Define dedicated `FilterInput` / `OrderByInput` input types with typed fields for each filter criterion'
34
+ avoid: 'Accepting a JSON string or raw scalar as a filter parameter — loses type safety, IDE auto-complete, and validation at the schema level'
@@ -0,0 +1,36 @@
1
+ id: libs-backend-python
2
+ category: tooling
3
+ tags:
4
+ - python
5
+ - backend
6
+ priority: 22
7
+ content:
8
+ constraints:
9
+ - 'DO NOT use requirements.txt. Use uv (preferred) or Poetry with pyproject.toml. Lock file (uv.lock or poetry.lock) must be committed.'
10
+ - 'DO NOT use print() for logging. Use structlog with JSON output.'
11
+ - 'DO NOT use unittest.TestCase. Use pytest with function-based tests and fixtures.'
12
+ - 'DO NOT use bare assert in production code. The -O flag strips assert statements. Use explicit if/raise instead.'
13
+ guidelines:
14
+ - 'uv 0.5+ — package management. uv sync, uv run. Commit uv.lock.'
15
+ - 'pytest 8+ / pytest-asyncio / pytest-cov — testing. Use fixtures, parametrize, and coverage reports.'
16
+ - 'httpx 0.28+ — sync/async HTTP client. Use ASGITransport for FastAPI integration tests.'
17
+ - 'structlog 24+ — structured JSON logging. Bind request_id and user_id to the context.'
18
+ - 'ruff — lint and format (replaces flake8, black, isort). Configure in pyproject.toml [tool.ruff].'
19
+ - 'mypy 1.10+ or pyright — static type checking in strict mode. Enforce as a CI gate.'
20
+ - 'pydantic-settings 2+ — environment variable loading and validation. Single source of truth for config.'
21
+ - 'tenacity 9+ — retry logic with exponential backoff. Use for external API calls and transient failure recovery.'
22
+ - 'Great Expectations 1+ or pandera — pipeline input/output data quality validation.'
23
+ - 'polars 1+ / duckdb 1+ — core data processing stack. Works in conjunction with data-pipeline-python rule.'
24
+ decision_table:
25
+ - when: 'Package management is needed'
26
+ then: 'Use uv + pyproject.toml + uv.lock'
27
+ avoid: 'pip + requirements.txt (no lock file guarantees), conda (heavy, slow CI)'
28
+ - when: 'Lint and format tooling is needed'
29
+ then: 'Use ruff as the single tool for lint and format'
30
+ avoid: 'flake8 + black + isort (fragmented config, slower CI)'
31
+ - when: 'Data quality validation is needed'
32
+ then: 'Great Expectations (batch pipeline) or pandera (DataFrame schema)'
33
+ avoid: 'Scattered manual assert statements inside pipeline code (untestable, no reporting)'
34
+ - when: 'HTTP client is needed'
35
+ then: 'Use httpx (supports both sync and async with a single API)'
36
+ avoid: 'requests (no async support), aiohttp (complex low-level API)'
@@ -0,0 +1,43 @@
1
+ id: libs-backend-ts
2
+ category: tooling
3
+ tags:
4
+ - typescript
5
+ - nestjs
6
+ - backend
7
+ priority: 25
8
+ content:
9
+ constraints:
10
+ - 'DO NOT use moment.js or dayjs. Use date-fns 4+ (tree-shakeable, immutable, functional API) — import individual functions only.'
11
+ - 'DO NOT use jsonwebtoken. Use jose 6+ (Web Crypto API, edge-compatible, no native binary dependencies).'
12
+ - 'DO NOT use Express APIs (req/res) directly in NestJS handlers. Route through the NestJS platform adapter layer.'
13
+ - 'DO NOT import lodash as a full bundle (import _ from "lodash"). Prefer native JS (structuredClone, Object.groupBy, Array.at) first; only then use individual lodash imports.'
14
+ - 'DO NOT use node-fetch or got for HTTP calls inside NestJS. Use @nestjs/axios (HttpModule) or native fetch().'
15
+ - 'DO NOT use winston, morgan, or console.log for application logging. Use pino 9+ via nestjs-pino 4+ — it fully replaces the NestJS Logger and provides best-in-class JSON serialization performance.'
16
+ guidelines:
17
+ - 'class-validator 0.14+ / class-transformer 0.5+ — DTO validation and serialization. Always enable whitelist: true in ValidationPipe.'
18
+ - '@nestjs/graphql 13+ / @nestjs/apollo 13+ / @apollo/server 5+ — GraphQL API layer. Use code-first approach with TypeScript decorators.'
19
+ - '@graphql-codegen/cli 6+ / client-preset 5+ — generate type-safe GraphQL operation types from the SDL at build time.'
20
+ - 'date-fns 4+ / date-fns-tz 3+ — date manipulation and timezone handling. Always import individual functions (e.g., import { format } from "date-fns").'
21
+ - 'jose 6+ — JWT signing, verification, JWK/JWKS handling. Use SignJWT / jwtVerify / createRemoteJWKSet.'
22
+ - 'pino 9+ / nestjs-pino 4+ — structured JSON logging. Bootstrap with LoggerModule.forRoot() to replace the NestJS Logger across all modules automatically.'
23
+ - 'rxjs 7+ — reactive patterns for NestJS interceptors, guards, and event streams. Prefer operators over manual Promise chains.'
24
+ - 'vitest 4+ / @nestjs/testing / supertest 7+ — unit and e2e testing. ESM-native; no ts-jest or @swc/jest configuration required.'
25
+ - 'pg 8+ / @prisma/adapter-pg 7+ — Prisma driver adapter. Configure connection pool size (max, idleTimeoutMillis) explicitly.'
26
+ - 'typescript 5+ with strict: true / @swc/core — type checking and fast transpilation in development and CI.'
27
+ - 'axios via @nestjs/axios HttpModule — outbound HTTP calls that require interceptors, retry logic, or request/response transformation.'
28
+ decision_table:
29
+ - when: 'JWT authentication is needed'
30
+ then: 'Use jose 6+ (SignJWT, jwtVerify, createRemoteJWKSet)'
31
+ avoid: 'jsonwebtoken — not Web Crypto compatible, not edge-runtime safe'
32
+ - when: 'Date manipulation or formatting is needed'
33
+ then: 'Use date-fns 4+ with individual function imports'
34
+ avoid: 'moment.js (mutable, large bundle), dayjs (non-standard plugin model)'
35
+ - when: 'A utility function is needed (e.g., deep clone, groupBy)'
36
+ then: 'Use native JS first (structuredClone, Object.groupBy); only fall back to individual lodash imports'
37
+ avoid: "lodash full bundle import (import _ from 'lodash')"
38
+ - when: 'Schema validation outside of DTOs is needed (e.g., env vars, external payloads)'
39
+ then: 'Use zod with parse/safeParse'
40
+ avoid: 'joi (CommonJS-only API), manual type guards (brittle, untestable)'
41
+ - when: 'Structured application logging is needed'
42
+ then: 'Use pino 9+ via nestjs-pino 4+ (LoggerModule.forRoot)'
43
+ avoid: 'winston (slow JSON serialization), morgan (HTTP-only), console.log (unstructured)'
@@ -0,0 +1,42 @@
1
+ id: libs-frontend-app
2
+ category: tooling
3
+ tags:
4
+ - dart
5
+ - flutter
6
+ - frontend
7
+ priority: 15
8
+ content:
9
+ constraints:
10
+ - 'DO NOT use the http package for API calls. Use dio 5+ — it provides interceptors, retry, cancellation, and multipart support.'
11
+ - 'DO NOT use Provider or Bloc for state management. Use flutter_riverpod 2+ with riverpod_annotation and riverpod_generator for code-gen-based providers.'
12
+ - 'DO NOT write data classes manually (==, hashCode, copyWith, toJson). Use freezed 2+ with build_runner to generate them.'
13
+ - 'DO NOT use Navigator 1.0 (push/pop). Use go_router 14+ for declarative, deep-link-ready routing.'
14
+ - 'DO NOT manually implement JSON serialization with dart:convert. Use json_annotation 4+ / json_serializable 6+ (or freezed fromJson/toJson) with build_runner.'
15
+ guidelines:
16
+ - 'flutter_riverpod 2+ / riverpod_annotation 2+ / riverpod_generator 2+ — state management. Use @riverpod annotation; run build_runner to generate provider code.'
17
+ - 'freezed 2+ / freezed_annotation 2+ — immutable data models with union types. Annotate with @freezed and generate via build_runner.'
18
+ - 'go_router 14+ — declarative routing. Use context.go() for replacement and context.push() for stack navigation. Define all routes in a central GoRouter instance.'
19
+ - 'dio 5+ — HTTP networking. Create a single central Dio instance (registered via Riverpod) with baseUrl, headers, and interceptors configured.'
20
+ - 'shared_preferences 2+ — non-sensitive key-value storage (settings, flags). flutter_secure_storage 9+ — sensitive data (tokens, credentials).'
21
+ - 'cached_network_image 3+ — network image display with automatic disk and memory caching, placeholder, and errorWidget support. Prefer over Image.network to avoid memory waste and lack of offline cache.'
22
+ - 'json_annotation 4+ / json_serializable 6+ — JSON code generation for models not using freezed.'
23
+ - 'build_runner 2+ — code generation orchestrator. Use dart run build_runner watch in development and dart run build_runner build --delete-conflicting-outputs in CI.'
24
+ - 'mocktail 1+ — test mocking without code generation. Uses Dart-native class extension syntax; no annotation required.'
25
+ - 'very_good_analysis 7+ — strict lint ruleset. Treat warnings as errors in CI (--fatal-warnings flag).'
26
+ - 'intl 0.19+ or easy_localization 3+ — i18n based on ARB files. Use intl for minimal dependencies; use easy_localization for runtime locale switching with context.tr().'
27
+ decision_table:
28
+ - when: 'HTTP API call is needed'
29
+ then: 'Use a central dio 5+ instance injected via Riverpod (ref.watch(dioProvider))'
30
+ avoid: 'http package (no interceptors), raw HttpClient (verbose, no retry support)'
31
+ - when: 'Local data persistence is needed'
32
+ then: 'Use shared_preferences for non-sensitive KV data; use flutter_secure_storage for tokens and credentials'
33
+ avoid: 'SQLite or Hive for simple key-value needs — overkill with unnecessary schema overhead'
34
+ - when: 'Network image needs to be displayed'
35
+ then: 'Use cached_network_image 3+ with placeholder and errorWidget configured'
36
+ avoid: 'Image.network — no disk cache, no memory management, no offline support'
37
+ - when: 'Test mocking is needed'
38
+ then: 'Use mocktail 1+ (class-based mocking, no code generation)'
39
+ avoid: 'mockito — requires code generation (@GenerateMocks), higher boilerplate'
40
+ - when: 'Code generation is required (freezed, riverpod_generator, json_serializable)'
41
+ then: 'Run build_runner 2+ (watch in dev, build --delete-conflicting-outputs in CI)'
42
+ avoid: 'Manually writing generated code — error-prone and breaks on regeneration'
@@ -0,0 +1,49 @@
1
+ id: libs-frontend-web
2
+ category: tooling
3
+ tags:
4
+ - typescript
5
+ - react
6
+ - nextjs
7
+ - frontend
8
+ priority: 20
9
+ content:
10
+ constraints:
11
+ - 'DO NOT use moment.js or dayjs. Use date-fns 4+ as the single standard — import individual functions only.'
12
+ - 'DO NOT use react-icons. Use lucide-react with named imports for a consistent design language and tree-shakeability.'
13
+ - 'DO NOT use axios on the client side. Use native fetch() to integrate with Next.js caching and revalidation mechanisms.'
14
+ - 'DO NOT write conditional className strings manually. Use the cn() utility (clsx + tailwind-merge) and cva for variant-based styling.'
15
+ - 'DO NOT install additional UI component libraries (MUI, Ant Design, Chakra UI) alongside shadcn/ui. Extend shadcn/ui primitives instead.'
16
+ - 'DO NOT use Redux, Recoil, or MobX for UI state. Use zustand 4+ for client UI state; delegate server/remote state to Apollo Client.'
17
+ guidelines:
18
+ - '@apollo/client 4+ / @apollo/experimental-nextjs-app-support 0.13+ — GraphQL data fetching in App Router. Use ApolloNextAppProvider in the root layout.'
19
+ - '@graphql-codegen/cli 6+ / client-preset 5+ — generate type-safe operation types (TypedDocumentNode) from the GraphQL schema at build time.'
20
+ - 'tailwindcss 4+ — utility-first styling with CSS variable design tokens. Define semantic tokens in globals.css.'
21
+ - 'clsx 2+ / tailwind-merge 3+ — compose the cn() utility for conflict-free class merging.'
22
+ - 'class-variance-authority 0.7+ — multi-variant component styling (e.g., Button with size and intent variants).'
23
+ - 'zustand 4+ — client UI state (modals, multi-step forms, sidebars). Keep server/remote state in Apollo Client cache; do not duplicate it in zustand.'
24
+ - 'next-intl 4+ — i18n with server component message loading and the useTranslations hook in client components.'
25
+ - 'next-themes — dark/light mode theming. Wrap the root layout with ThemeProvider; read the theme via useTheme.'
26
+ - 'recharts 2+ — data visualization. Always render inside a "use client" boundary component to avoid hydration errors.'
27
+ - 'sonner — toast notifications. Mount a single <Toaster /> in the root layout; call toast() anywhere.'
28
+ - 'date-fns 4+ — date formatting and manipulation. Import individual functions (e.g., import { format, parseISO } from "date-fns").'
29
+ - 'isomorphic-dompurify — sanitize UGC HTML before rendering with dangerouslySetInnerHTML. Never skip sanitization.'
30
+ - 'vitest 4+ / @testing-library/react — unit and component testing. Use userEvent over fireEvent; ESM-native, no separate transpiler needed.'
31
+ decision_table:
32
+ - when: 'GraphQL data fetching is needed in App Router'
33
+ then: 'Use @apollo/client 4+ with @apollo/experimental-nextjs-app-support (ApolloNextAppProvider)'
34
+ avoid: 'urql (less Next.js integration), raw fetch with manual cache keys'
35
+ - when: 'Date manipulation or formatting is needed'
36
+ then: 'Use date-fns 4+ with individual function imports'
37
+ avoid: 'dayjs (removed from this project — migrate to date-fns)'
38
+ - when: 'Icons are needed in the UI'
39
+ then: 'Use lucide-react with named imports (e.g., import { ChevronRight } from "lucide-react")'
40
+ avoid: 'react-icons (inconsistent design, large bundle), inline SVG (hard to maintain)'
41
+ - when: 'Form input validation is needed'
42
+ then: 'Use zod schema + react-hook-form with @hookform/resolvers/zod'
43
+ avoid: 'yup (larger API surface), manual validation logic in onChange handlers'
44
+ - when: 'User-generated HTML content must be rendered'
45
+ then: 'Sanitize with isomorphic-dompurify first, then render with dangerouslySetInnerHTML'
46
+ avoid: 'Rendering unsanitized HTML — XSS risk'
47
+ - when: 'Client UI state is needed (modal open, wizard step, sidebar)'
48
+ then: 'Use a zustand store slice'
49
+ avoid: 'Redux or Recoil (overkill); useState is sufficient for single-component-scoped state only'
@@ -0,0 +1,10 @@
1
+ id: naming-convention
2
+ category: convention
3
+ tags:
4
+ - general
5
+ - naming
6
+ priority: 75
7
+ content:
8
+ constraints: []
9
+ guidelines:
10
+ - 'Use kebab-case for directory names.'
@@ -0,0 +1,31 @@
1
+ id: nestjs-graphql
2
+ category: framework
3
+ tags:
4
+ - typescript
5
+ - nestjs
6
+ - graphql
7
+ priority: 43
8
+ content:
9
+ constraints:
10
+ - 'DO NOT put business logic in Resolvers. Resolvers are thin orchestrators — delegate all domain logic to Services, identical to the Controller rule in nestjs.yaml.'
11
+ - "DO NOT access raw GraphQL context directly. Use typed `@Args('input') input: CreateUserInput` decorators for argument extraction. Direct `context.args` access bypasses NestJS type safety and validation pipe integration."
12
+ - 'DO NOT issue DB queries inside `@ResolveField()` methods. Inject and call a DataLoader instead — direct repository calls in field resolvers cause N+1 queries at runtime.'
13
+ - 'DO NOT expose unauthenticated `@Subscription()` endpoints. Apply `@UseGuards(GqlAuthGuard)` or implement a `filter` function that validates subscriber identity before yielding events.'
14
+ - 'DO NOT write manual SDL files in a code-first NestJS GraphQL project. TypeScript decorators (`@ObjectType`, `@Field`, `@InputType`) are the single source of truth — the schema is auto-generated from them.'
15
+ guidelines:
16
+ - 'Structure resolvers with `@Resolver(() => Entity)` at the class level, `@Query()` / `@Mutation()` for top-level operations, and `@ResolveField()` for field-level data loading. One resolver file per domain entity.'
17
+ - 'Register DataLoaders as request-scoped NestJS providers. Use `@nestjs/dataloader` or a custom `DataLoaderFactory` — request scoping ensures per-request batching without cross-request data leakage.'
18
+ - "Add `{ description: '...' }` to every `@ObjectType()`, `@InputType()`, `@ArgsType()`, and `@Field()` decorator. Descriptions are emitted into the auto-generated SDL and serve as living API documentation."
19
+ - 'Apply query complexity and depth limiting via `graphql-query-complexity` + the NestJS GraphQL complexity plugin. Set a maximum complexity budget per request to prevent DoS through deeply nested or highly multiplied queries.'
20
+ - 'Define custom scalars (`DateTime`, `JSON`, `UUID`) with `@Scalar()` decorator classes and register them globally in the GraphQL module config. Consistent scalar handling prevents serialization mismatches between the schema and runtime values.'
21
+ - 'Apply `@UseGuards()` and `@UseInterceptors()` at the resolver or method level using `GqlExecutionContext.create(context)` to extract the GraphQL-specific context. Reuse the same Guard and Interceptor classes as REST controllers — `ExecutionContext` switching is the only adapter needed.'
22
+ decision_table:
23
+ - when: 'A field resolver needs to load related entity data (e.g., user.posts)'
24
+ then: 'Use `@ResolveField()` backed by a request-scoped DataLoader that batches IDs and issues a single DB query per request cycle'
25
+ avoid: 'Calling the repository directly inside `@ResolveField()` — each parent node triggers a separate query (N+1)'
26
+ - when: 'Real-time data push is required (e.g., live notifications, order status updates)'
27
+ then: 'Use `@Subscription()` with Redis PubSub (`graphql-redis-subscriptions`) — horizontally scalable across multiple server instances'
28
+ avoid: 'In-memory PubSub (`new PubSub()`) — events are not shared across instances, causing silent message loss in multi-pod deployments'
29
+ - when: 'Authentication or authorization is required on a resolver'
30
+ then: 'Apply `@UseGuards(GqlAuthGuard)` at the class or method level; extract user from `GqlExecutionContext.create(ctx).getContext().req.user`'
31
+ avoid: 'Manual JWT parsing inside the resolver function body — authentication is a cross-cutting concern and must not bleed into business logic'
@@ -0,0 +1,26 @@
1
+ id: nestjs
2
+ category: framework
3
+ tags:
4
+ - typescript
5
+ - nestjs
6
+ priority: 45
7
+ content:
8
+ constraints:
9
+ - 'DO NOT use @Res() or @Response() decorator to send responses directly. It bypasses Interceptors, Exception Filters, and built-in serialization. Return values from the handler instead.'
10
+ - 'DO NOT put business logic in Controllers. Controllers are thin orchestrators — delegate all logic to Services.'
11
+ - 'DO NOT use forwardRef() to work around circular dependencies. Redesign the module boundary or extract a shared module instead.'
12
+ - 'DO NOT access process.env directly in service or controller classes. Inject ConfigService from @nestjs/config and validate the env schema at application startup.'
13
+ - 'DO NOT use console.log for application logging. Inject NestJS Logger or a custom logger (e.g., pino, Winston) through the DI system.'
14
+ guidelines:
15
+ - 'Organize by feature module: one module per domain (e.g., users/users.module.ts) co-locating its controller, service, and DTOs.'
16
+ - 'Define request/response DTOs with class-validator decorators. Never expose entities directly as API responses.'
17
+ - 'Register global pipes, filters, and guards in main.ts bootstrap (e.g., app.useGlobalPipes(new ValidationPipe({ whitelist: true }))).'
18
+ - 'Extend HttpException for custom business exceptions to integrate with the built-in exception filter layer.'
19
+ - 'For REST APIs, annotate controllers with @ApiOperation and DTOs with @ApiProperty via @nestjs/swagger. Omit for GraphQL — the SDL schema is the contract.'
20
+ decision_table:
21
+ - when: 'Cross-cutting concern needs access to ExecutionContext (e.g., role check, auth)'
22
+ then: 'Use a Guard (@CanActivate) — it runs after middleware, before interceptors, and has access to the handler metadata'
23
+ avoid: 'Using middleware for auth — middleware lacks ExecutionContext and @SetMetadata access'
24
+ - when: 'Need to transform, wrap, or cache the response, or measure execution time'
25
+ then: 'Use an Interceptor — it wraps the handler execution with RxJS Observable'
26
+ avoid: 'Using middleware for response transformation — middleware runs before the route handler'
@@ -0,0 +1,34 @@
1
+ id: nextjs
2
+ category: framework
3
+ tags:
4
+ - typescript
5
+ - react
6
+ - nextjs
7
+ - app-router
8
+ priority: 50
9
+ content:
10
+ constraints:
11
+ - "DO NOT import server-only code (db clients, secrets, internal APIs) in Client Components. Use the 'server-only' package to enforce the boundary."
12
+ - 'DO NOT store secrets in NEXT_PUBLIC_ environment variables. Only NEXT_PUBLIC_ vars are exposed to the browser.'
13
+ - 'DO NOT use next/router. Use next/navigation (useRouter, usePathname, useSearchParams) in App Router.'
14
+ guidelines:
15
+ - 'Use the Next.js file conventions: page.tsx, layout.tsx, loading.tsx, error.tsx, not-found.tsx.'
16
+ - "Co-locate Server Actions in a dedicated file (e.g., actions.ts) with 'use server' at the top."
17
+ - 'Use next/image for all images with explicit width/height or fill+sizes.'
18
+ - 'Use next/font in root layout, apply via CSS variable.'
19
+ - 'Use middleware.ts only for cross-cutting concerns: auth redirects, locale detection, header injection.'
20
+ - 'Export generateMetadata or a static metadata object from every public-facing page.tsx. Include title, description, and Open Graph fields for SEO crawlers and social sharing.'
21
+ - 'Apply JSON-LD structured data markup for GEO (Generative Engine Optimization). Inject <script type="application/ld+json"> with schema.org-based structured data in public pages to optimize for AI search engines (SGE, Perplexity) and traditional search engines.'
22
+ decision_table:
23
+ - when: 'Component needs event handlers, useState, useEffect, or browser APIs'
24
+ then: "Add 'use client' to that component only"
25
+ avoid: "Adding 'use client' to a parent — push it to the smallest leaf"
26
+ - when: 'Data needs to be fetched for a page'
27
+ then: 'Fetch in Server Component (page.tsx, layout.tsx) with async/await'
28
+ avoid: 'useEffect + fetch in Client Component for initial page data'
29
+ - when: 'Form submission or data mutation'
30
+ then: 'Server Action via form action or startTransition'
31
+ avoid: 'POST route.ts for simple mutations'
32
+ - when: 'API endpoint for external consumers or webhooks'
33
+ then: 'route.ts with explicit HTTP method exports (GET, POST)'
34
+ avoid: 'Server Actions for external API endpoints'
@@ -0,0 +1,30 @@
1
+ id: prisma-postgresql
2
+ category: database
3
+ tags:
4
+ - typescript
5
+ - prisma
6
+ - postgresql
7
+ priority: 40
8
+ content:
9
+ constraints:
10
+ - 'DO NOT use $queryRawUnsafe with string interpolation or concatenation. It creates SQL injection vulnerabilities. Use tagged template $queryRaw`...${variable}` which auto-escapes, or use positional parameters ($1, $2) with $queryRawUnsafe.'
11
+ - 'DO NOT return Prisma model objects directly as API responses. Models may contain sensitive fields (password, tokens, deletedAt). Use select to pick specific fields or map to a response DTO.'
12
+ - 'DO NOT define mutable models without an updatedAt field. Add `updatedAt DateTime @updatedAt` to every model that can be modified after creation.'
13
+ - 'DO NOT use $use() middleware — it is removed in Prisma v7. Use Client Extensions ($extends) with query hooks instead.'
14
+ - 'DO NOT use prisma db push in production. It can cause data loss and has no migration history. Use prisma migrate deploy with versioned migration files only.'
15
+ guidelines:
16
+ - 'Use the prisma-client generator with an explicit output path: generator client { provider = "prisma-client"; output = "./generated/prisma/client" }. The legacy prisma-client-js provider is deprecated in v7.'
17
+ - 'Configure a driver adapter explicitly. For PostgreSQL, use @prisma/adapter-pg with pool settings (max connections, idleTimeoutMillis, connectionTimeoutMillis) tuned to your environment.'
18
+ - 'Add @@index on fields used in where, orderBy, and relation foreign keys. Use composite indexes @@index([fieldA, fieldB]) for multi-column filter patterns.'
19
+ - 'Set explicit timeout and maxWait on interactive transactions to match your business requirements — the defaults (timeout: 5000ms, maxWait: 2000ms) may be too short for complex operations.'
20
+ - 'Centralize configuration in prisma.config.ts (datasource URL, migration path, seed script). The url and directUrl fields in the schema.prisma datasource block are deprecated in v7.'
21
+ - 'Implement soft delete via Client Extension ($extends query hook) that injects where: { deletedAt: null } into find queries automatically — not via the removed $use() middleware.'
22
+ - 'Prefer cursor-based pagination (cursor + take) over offset-based (skip + take) for large tables. Offset pagination degrades as page depth increases; cursor pagination leverages indexes consistently.'
23
+ - 'In serverless or containerized environments, configure an external connection pooler (e.g., PgBouncer) or set an explicit connection_limit on @prisma/adapter-pg to prevent database max connection exhaustion.'
24
+ decision_table:
25
+ - when: 'Query requires window functions, CTEs, complex aggregations, or PostgreSQL-specific syntax not supported by Prisma Client API'
26
+ then: 'Use $queryRaw with tagged template literals for automatic escaping and type safety'
27
+ avoid: 'Overusing raw SQL for queries that Prisma Client API can express — lose type safety and query validation'
28
+ - when: 'Transaction involves multiple writes where later queries depend on earlier results'
29
+ then: 'Use interactive transaction ($transaction(async (tx) => { ... })) with explicit timeout/maxWait'
30
+ avoid: 'Using batch transaction ($transaction([...])) when queries are interdependent — batch does not guarantee execution order access'
@@ -0,0 +1,31 @@
1
+ id: python
2
+ category: language
3
+ tags:
4
+ - python
5
+ priority: 55
6
+ content:
7
+ constraints:
8
+ - 'DO NOT use Any type hint. Use object or concrete generics instead.'
9
+ - 'DO NOT use mutable default arguments (def f(items: list = [])). Use None sentinel + factory pattern inside the function body.'
10
+ - 'DO NOT use bare except: or except Exception:. Catch specific exception types.'
11
+ - 'DO NOT use from module import *. Always use explicit imports.'
12
+ - 'DO NOT use string-based type checking (type(x) == str). Use isinstance() or Protocol.'
13
+ - 'DO NOT use # type: ignore without an error code. Always specify the code (e.g., # type: ignore[arg-type]).'
14
+ guidelines:
15
+ - 'Annotate all function parameters and return types, including -> None.'
16
+ - 'Use Pydantic V2 BaseModel for DTOs, config, and schemas. Use model_validator / field_validator (V1 deprecated validator is forbidden).'
17
+ - 'Leverage TypeAlias, TypeVar, ParamSpec, TypedDict, and Literal for expressive type annotations.'
18
+ - 'Isolate business logic in *_logic.py (pure functions). Keep services and routers as thin orchestrators.'
19
+ - 'Use @dataclass(frozen=True) for immutable value objects that do not require runtime validation.'
20
+ - 'Use pathlib.Path instead of os.path for all filesystem operations.'
21
+ - 'Use f-strings only. Avoid % formatting and .format().'
22
+ decision_table:
23
+ - when: 'Structured data requires validation or serialization'
24
+ then: 'Use Pydantic V2 BaseModel'
25
+ avoid: 'plain dict, TypedDict (no runtime validation)'
26
+ - when: 'Immutable value object without runtime validation is needed'
27
+ then: 'Use @dataclass(frozen=True)'
28
+ avoid: 'Pydantic (unnecessary overhead for pure value objects)'
29
+ - when: 'Runtime type narrowing is needed'
30
+ then: 'Use isinstance() or model_validate()'
31
+ avoid: 'type() comparison, hasattr() (fragile and non-idiomatic)'
@@ -0,0 +1,11 @@
1
+ id: react-typescript
2
+ category: framework
3
+ tags:
4
+ - typescript
5
+ - react
6
+ priority: 60
7
+ content:
8
+ constraints:
9
+ - 'DO NOT use React.FC or FC. Type props directly and destructure them.'
10
+ guidelines:
11
+ - 'Use readonly for array and object props.'
@@ -0,0 +1,14 @@
1
+ id: role-persona
2
+ category: persona
3
+ tags:
4
+ - general
5
+ - persona
6
+ priority: 90
7
+ content:
8
+ constraints:
9
+ - "DO NOT write patronizing tutorials (e.g., 'First, let me explain what React is...')."
10
+ guidelines:
11
+ - 'You are an expert Senior Full-Stack Developer.'
12
+ - 'Assume the user is a senior developer, but may be unfamiliar with specific domains or patterns.'
13
+ - 'When choosing a pattern, library, or architectural approach, briefly explain WHY it was chosen over alternatives.'
14
+ - 'Focus on high-level architecture, edge cases, performance optimization, and maintainability.'
@@ -0,0 +1,36 @@
1
+ id: shadcn-ui
2
+ category: ui
3
+ tags:
4
+ - typescript
5
+ - react
6
+ - shadcn-ui
7
+ - tailwind
8
+ priority: 35
9
+ content:
10
+ constraints:
11
+ - "DO NOT reimplement components already provided by Shadcn (Dialog, Sheet, Select, Toast, etc.). Use 'npx shadcn@latest add <component>' instead."
12
+ - 'DO NOT directly edit Shadcn source files (components/ui/*.tsx). Extend via wrapper components or customize via className.'
13
+ - 'DO NOT abuse Tailwind arbitrary values (e.g., w-[327px]). Define design tokens (spacing, color) in tailwind.config.ts and reference them.'
14
+ - 'DO NOT use inline styles (style={}) for static values. Only exception: runtime-computed dynamic values. Use Tailwind classes for all static styles.'
15
+ guidelines:
16
+ - 'Check the Shadcn component catalog first (https://ui.shadcn.com/docs/components) before implementing any new UI element.'
17
+ - 'Use the cn() utility (clsx + tailwind-merge) for conditional class merging. Prefer cn(base, condition && variant) over string templates or manual conditionals.'
18
+ - 'Follow Shadcn composition patterns. Compose complex components from sub-components (e.g., Dialog = DialogTrigger + DialogContent + DialogHeader + DialogTitle + DialogDescription).'
19
+ - 'Use cva (class-variance-authority) for components with multiple variants. Do not branch classes with prop conditionals.'
20
+ - 'Maintain CSS variable-based theme system. Use hsl(var(--primary)) color format. Map CSS variables to Tailwind tokens in tailwind.config.ts.'
21
+ - 'Apply responsive styles mobile-first. Use sm:, md:, lg: breakpoint prefixes in order. Avoid desktop-first (max-*:) patterns.'
22
+ - 'Preserve built-in accessibility from Shadcn (Radix UI). For icon-only buttons or visual-only elements, always add aria-label or <span className="sr-only"> for screen reader text.'
23
+ - "Use named imports for individual icons (e.g., import { ChevronDown } from 'lucide-react'). Never import the entire icon namespace."
24
+ decision_table:
25
+ - when: 'UI element exists in Shadcn catalog or can be composed from Radix primitives'
26
+ then: 'Use Shadcn component'
27
+ avoid: 'Custom implementation from scratch'
28
+ - when: 'Shadcn has no matching component and domain-specific complex interaction is needed'
29
+ then: 'Write a custom component'
30
+ avoid: 'Forcing Shadcn usage or wrapping unrelated primitives'
31
+ - when: 'Component needs conditional styling or multiple visual variants'
32
+ then: 'Define variant map with cva'
33
+ avoid: 'Branching className strings with if/ternary in JSX'
34
+ - when: 'Styling approach is needed'
35
+ then: 'Tailwind classes by default'
36
+ avoid: 'CSS Modules (only for complex animations/keyframes or third-party style overrides)'
@@ -0,0 +1,32 @@
1
+ id: sqlalchemy
2
+ category: database
3
+ tags:
4
+ - python
5
+ - sqlalchemy
6
+ - postgresql
7
+ priority: 38
8
+ content:
9
+ constraints:
10
+ - 'DO NOT use legacy 1.x style session.query(). Use 2.0 style select() / insert() / update() statements.'
11
+ - 'DO NOT execute raw SQL strings directly (except in Alembic migrations). Use ORM or text() with bound parameters to prevent SQL injection.'
12
+ - 'DO NOT call session.commit() in multiple scattered places. Use Unit of Work pattern — commit once at the service layer boundary.'
13
+ - 'DO NOT omit created_at / updated_at on models. Use server_default=func.now() and onupdate=func.now().'
14
+ - 'DO NOT modify the schema without Alembic. Use alembic revision --autogenerate and manually review the generated migration.'
15
+ guidelines:
16
+ - 'Use Mapped[T] / mapped_column() declarative mapping (SQLAlchemy 2.0 type-safe style).'
17
+ - 'Declare relationships as Mapped[list["Child"]] with relationship(back_populates=...) explicitly set.'
18
+ - 'Use AsyncSession + async_sessionmaker to match the FastAPI async stack.'
19
+ - 'Implement soft delete with deleted_at: Mapped[datetime | None] and apply the filter by default in all queries.'
20
+ - 'Use Python StrEnum + Mapped[MyEnum] for enum columns (stored as strings, migration-safe).'
21
+ - 'Declare indexes and constraints explicitly in __table_args__: composite indexes, unique constraints.'
22
+ - 'Prevent N+1: always specify eager loading strategy when accessing relationships — selectinload() for 1:N (separate IN query), joinedload() for N:1/1:1 (JOIN). Never rely on lazy="select" default.'
23
+ decision_table:
24
+ - when: 'Simple CRUD operations are needed'
25
+ then: 'Use SQLAlchemy ORM (select, insert, update)'
26
+ avoid: 'Raw SQL strings (no type safety, SQL injection risk)'
27
+ - when: 'Complex analytical query with window functions is needed'
28
+ then: 'Use DuckDB or raw SQL via text() with bound parameters'
29
+ avoid: 'Forcing complex window functions through the ORM (verbose and unreadable)'
30
+ - when: 'Schema change is required'
31
+ then: 'Use Alembic --autogenerate + manual review'
32
+ avoid: 'Manual SQL DDL (untracked, causes environment drift)'
@@ -0,0 +1,22 @@
1
+ id: typescript
2
+ category: language
3
+ tags:
4
+ - typescript
5
+ priority: 65
6
+ content:
7
+ constraints:
8
+ - 'DO NOT use interface. Use type only.'
9
+ - 'DO NOT use enum. Use as const objects instead.'
10
+ - 'DO NOT use any. Use unknown with type narrowing (Zod / type guards).'
11
+ - 'DO NOT use non-null assertion (!). Use optional chaining (?.) and nullish coalescing (??) instead.'
12
+ - 'DO NOT use .then() chains. Use async/await.'
13
+ - 'DO NOT throw raw strings. Use throw new Error(...) only. Type catch errors as unknown and narrow.'
14
+ guidelines:
15
+ - 'Use arrow functions only. Explicitly annotate return types for exported functions.'
16
+ - 'Use import type { ... } for type-only imports. Use absolute paths (@/...) only.'
17
+ - 'Use as const for static configuration objects.'
18
+ - 'Separate business logic into *.logic.ts files (pure functions). Keep stateless helpers in *.util.ts files (parsers, formatters).'
19
+ decision_table:
20
+ - when: 'Type assertion (as) seems necessary'
21
+ then: 'Prefer Zod .parse() or type guards to narrow the type safely'
22
+ avoid: 'Using as to bypass the type system without runtime validation'