@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,25 @@
1
+ Rule: Enforce Logging and Diagnostics
2
+ Requirements:
3
+ - AI MUST follow all `.ai/rules/*.md` files for every logging implementation.
4
+ - AI MUST use Serilog as the logging framework.
5
+ - AI MUST use structured logs with named properties.
6
+ - AI MUST configure Serilog at startup in `MauiProgram.cs` or `Program.cs`.
7
+ - AI MUST integrate logging with dependency injection.
8
+ - AI MUST apply log levels consistently: Debug/Information/Warning/Error/Fatal.
9
+ - AI MUST write logs to console and rolling file sink.
10
+ - AI MUST enforce file retention policy: daily rolling, retain 14 days, cap 100MB per file.
11
+ - AI MUST log operational events and exception context.
12
+ Prohibited:
13
+ - AI MUST NOT log secrets, tokens, passwords, API keys, or PII.
14
+ - AI MUST NOT use unstructured concatenated log strings when structured properties are applicable.
15
+ - AI MUST NOT leave verbose debug logging enabled in production defaults.
16
+ - AI MUST NOT swallow exceptions without logging context.
17
+ - AI MUST NOT bypass configured retention limits.
18
+ Patterns:
19
+ - `Log.Information("Processed order {OrderId}", orderId);`
20
+ - `Log.Error(ex, "Sync failed for {EntityId}", entityId);`
21
+ - Configure sinks in startup composition root.
22
+ - Use contextual enrichment (request id, correlation id) where available.
23
+ Examples:
24
+ - `builder.Logging.AddSerilog();`
25
+ - `.WriteTo.File("logs/app-.log", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 14, fileSizeLimitBytes: 104857600)`
@@ -0,0 +1,26 @@
1
+ Rule: Enforce .NET MAUI UI Rules
2
+ Requirements:
3
+ - AI MUST follow all `.ai/rules/*.md` files before producing MAUI code.
4
+ - AI MUST implement UI in XAML first.
5
+ - AI MUST use MAUI Shell with URI-based navigation.
6
+ - AI MUST use data binding for UI state and actions.
7
+ - AI MUST keep UI thread non-blocking by using async/await for long operations.
8
+ - AI MUST execute UI updates on the main thread when marshalling from background tasks.
9
+ - AI MUST keep code-behind minimal and UI-only.
10
+ - AI MUST expose user-facing state from ViewModels (`IsLoading`, `ErrorMessage`, etc.).
11
+ - AI MUST implement offline-first behavior where UI reads from local SQLite-backed state.
12
+ Prohibited:
13
+ - AI MUST NOT place business logic in XAML code-behind.
14
+ - AI MUST NOT perform direct database calls from Views.
15
+ - AI MUST NOT perform direct API calls from Views.
16
+ - AI MUST NOT use synchronous blocking operations in UI workflows.
17
+ - AI MUST NOT use `async void` except framework-required event handlers.
18
+ - AI MUST NOT use event-handler-centric architecture when commands are applicable.
19
+ Patterns:
20
+ - Bind properties with `{Binding ...}`.
21
+ - Bind actions to `ICommand` generated by `[RelayCommand]`.
22
+ - Navigate with `await Shell.Current.GoToAsync("route");`.
23
+ - Trigger startup/loading in `InitializeAsync()`.
24
+ Examples:
25
+ - `<Button Text="Save" Command="{Binding SaveCommand}" />`
26
+ - `await Shell.Current.GoToAsync("//home");`
@@ -0,0 +1,26 @@
1
+ Rule: Enforce MVVM with CommunityToolkit
2
+ Requirements:
3
+ - AI MUST follow all `.ai/rules/*.md` files and enforce strict MVVM separation.
4
+ - AI MUST implement ViewModels with `ObservableObject` from CommunityToolkit.Mvvm.
5
+ - AI MUST define bindable state using `[ObservableProperty]`.
6
+ - AI MUST define user actions using `[RelayCommand]`.
7
+ - AI MUST inject dependencies through constructors only.
8
+ - AI MUST keep constructors lightweight and move runtime work to `InitializeAsync()`.
9
+ - AI MUST call business logic through services only.
10
+ - AI MUST handle operation failures and expose safe user-facing error state.
11
+ Prohibited:
12
+ - AI MUST NOT implement manual `INotifyPropertyChanged` patterns.
13
+ - AI MUST NOT instantiate services directly inside ViewModels.
14
+ - AI MUST NOT call APIs directly from ViewModels.
15
+ - AI MUST NOT call SQLite directly from ViewModels.
16
+ - AI MUST NOT place navigation-independent business rules in ViewModels.
17
+ - AI MUST NOT use `async void` except framework-required handlers.
18
+ Patterns:
19
+ - `public partial class XViewModel : ObservableObject`
20
+ - `[ObservableProperty] private bool isLoading;`
21
+ - `[RelayCommand] private async Task LoadAsync()`
22
+ - Constructor injection: `XViewModel(IXService service)`
23
+ - ViewModel lifecycle default: transient registration; singleton only with explicit justification.
24
+ Examples:
25
+ - `builder.Services.AddTransient<LoginViewModel>();`
26
+ - `[RelayCommand] private async Task RefreshAsync() { ... }`
@@ -0,0 +1,24 @@
1
+ Rule: Enforce Packaging and Distribution
2
+ Requirements:
3
+ - AI MUST follow all `.ai/rules/*.md` files when defining release and distribution workflows.
4
+ - AI MUST use semantic versioning (`MAJOR.MINOR.PATCH`) for all releases.
5
+ - AI MUST publish release artifacts through GitHub Releases for every version.
6
+ - AI MUST include release notes for every published version.
7
+ - AI MUST produce platform-specific distributables for MAUI applications.
8
+ - AI MUST package Windows MAUI releases as MSIX artifacts.
9
+ - AI MUST package CLI releases as self-contained binaries per target platform.
10
+ - AI MUST maintain deterministic artifact naming that includes application name, version, and target platform.
11
+ Prohibited:
12
+ - AI MUST NOT publish unversioned release artifacts.
13
+ - AI MUST NOT ship debug builds as production release artifacts.
14
+ - AI MUST NOT skip release notes on published versions.
15
+ - AI MUST NOT mix preview and stable artifact channels without explicit labeling.
16
+ - AI MUST NOT bypass signing requirements where platform policy requires signing.
17
+ Patterns:
18
+ - GitHub Releases as canonical artifact distribution channel.
19
+ - Version tag format: `v<MAJOR>.<MINOR>.<PATCH>`.
20
+ - Artifact naming: `<app>-<version>-<platform>.<ext>`.
21
+ - Release workflow: build -> package -> sign (if required) -> publish artifacts -> publish release notes.
22
+ Examples:
23
+ - `MyApp-1.4.0-windows-x64.msix`
24
+ - `mycli-1.4.0-linux-x64`
@@ -0,0 +1,26 @@
1
+ Rule: Enforce Project Structure
2
+ Requirements:
3
+ - AI MUST follow this file and all `.ai/rules/*.md` files at all times.
4
+ - AI MUST use feature-based organization only.
5
+ - AI MUST keep single-level features only: `Features/<FeatureName>/`.
6
+ - AI MUST use this root structure: `Features/`, `Infrastructure/`, `Services/`, `Models/`, `Data/`, `Configuration/`.
7
+ - AI MUST place shared cross-feature business services in `Services/`.
8
+ - AI MUST place low-level technical services in `Infrastructure/` only.
9
+ - AI MUST keep feature-specific files inside their feature folder.
10
+ - AI MUST use standard naming: `<Name>Page.xaml`, `<Name>Page.xaml.cs`, `<Name>ViewModel.cs`, `<Name>Service.cs`.
11
+ Prohibited:
12
+ - AI MUST NOT create layer-based or mixed structure alternatives.
13
+ - AI MUST NOT create nested feature folders beyond one level.
14
+ - AI MUST NOT place business logic in `Infrastructure/`.
15
+ - AI MUST NOT scatter feature files across unrelated folders.
16
+ - AI MUST NOT invent non-standard naming conventions.
17
+ Patterns:
18
+ - `Features/Orders/OrdersPage.xaml`
19
+ - `Features/Orders/OrdersPage.xaml.cs`
20
+ - `Features/Orders/OrdersViewModel.cs`
21
+ - `Features/Orders/OrdersService.cs`
22
+ - `Data/DatabaseService.cs`
23
+ - `Data/Repositories/`
24
+ Examples:
25
+ - `Features/Auth/LoginPage.xaml`
26
+ - `Features/Auth/LoginViewModel.cs`
@@ -0,0 +1,29 @@
1
+ Rule: Enforce SQLite Data Layer
2
+ Requirements:
3
+ - AI MUST follow all `.ai/rules/*.md` files before generating data access code.
4
+ - AI MUST use `sqlite-net-pcl` for SQLite access.
5
+ - AI MUST use `SQLiteAsyncConnection` for all database operations.
6
+ - AI MUST initialize database at `Path.Combine(FileSystem.AppDataDirectory, "app.db")`.
7
+ - AI MUST define entities with sqlite-net attributes (`[Table]`, `[PrimaryKey]`, `[Indexed]` as needed).
8
+ - AI MUST centralize connection lifecycle in `DatabaseService`.
9
+ - AI MUST use repository classes for table access.
10
+ - AI MUST use transactions for multi-record write operations.
11
+ - AI MUST treat SQLite as primary local source for UI-facing reads.
12
+ - AI MUST persist API responses to SQLite before exposing updated state to ViewModels.
13
+ - AI MUST define explicit conflict handling policy during synchronization (merge or local-priority).
14
+ Prohibited:
15
+ - AI MUST NOT use direct SQL strings when repository methods can express the query.
16
+ - AI MUST NOT use synchronous DB operations.
17
+ - AI MUST NOT call SQLite from Views.
18
+ - AI MUST NOT call SQLite from ViewModels.
19
+ - AI MUST NOT store secrets in plaintext database fields.
20
+ - AI MUST NOT replace sqlite-net with other ORMs in this architecture.
21
+ - AI MUST NOT update UI state from API payloads before SQLite persistence in offline-first flows.
22
+ Patterns:
23
+ - `Data/DatabaseService.cs` manages connection and table creation.
24
+ - `Data/Repositories/<Entity>Repository.cs` encapsulates queries.
25
+ - API synchronization writes to repositories, then ViewModels load from repositories.
26
+ - Use `RunInTransactionAsync` or equivalent transactional pattern for grouped writes.
27
+ Examples:
28
+ - `_db = new SQLiteAsyncConnection(dbPath);`
29
+ - `await _db.CreateTableAsync<UserEntity>();`
@@ -0,0 +1,24 @@
1
+ Rule: Enforce Testing Standards
2
+ Requirements:
3
+ - AI MUST follow all `.ai/rules/*.md` files when generating tests or testable code.
4
+ - AI MUST define service dependencies behind interfaces to enable mocking.
5
+ - AI MUST inject dependencies into ViewModels and services through constructors.
6
+ - AI MUST keep ViewModels free of direct database and API calls to preserve unit testability.
7
+ - AI MUST write tests against behavior and public contracts, not private implementation details.
8
+ - AI MUST keep I/O-dependent logic behind abstractions to allow deterministic tests.
9
+ - AI MUST use async test methods for async production methods.
10
+ - AI MUST keep test data deterministic and isolated per test.
11
+ Prohibited:
12
+ - AI MUST NOT couple tests to external services, real network calls, or production databases.
13
+ - AI MUST NOT use static mutable shared state across tests.
14
+ - AI MUST NOT rely on execution order between tests.
15
+ - AI MUST NOT introduce synchronous wrappers around async code for tests.
16
+ - AI MUST NOT bypass dependency injection in tests by direct concrete instantiation when mocks/fakes are required.
17
+ Patterns:
18
+ - Mock service interfaces in ViewModel tests.
19
+ - Test command methods through ViewModel public API.
20
+ - Use in-memory or isolated SQLite test stores when persistence behavior must be validated.
21
+ - Organize tests by feature and target class behavior.
22
+ Examples:
23
+ - `var vm = new LoginViewModel(mockAuthService.Object);`
24
+ - `await vm.LoginCommand.ExecuteAsync(null);`
@@ -0,0 +1,29 @@
1
+ Rule: Enforce Retrofit API Integration
2
+ Requirements:
3
+ - AI MUST use Retrofit for all HTTP communication — annotated `@RestApi()` abstract classes.
4
+ - AI MUST provide one shared, configured Dio instance via a `@Riverpod(keepAlive: true)` provider in `core/network/dio_client.dart`.
5
+ - AI MUST include the `AuthInterceptor` on all Dio instances except the auth API client.
6
+ - AI MUST read `baseUrl` from `AppConfig` — never hardcode it.
7
+ - AI MUST prefix all API paths with `/api/v1/`.
8
+ - AI MUST provide each API client via a `@riverpod` function using the shared `dioClientProvider`.
9
+ - AI MUST co-locate API client files with the feature they serve.
10
+ - AI MUST use Freezed + `json_serializable` for all request and response models.
11
+ - AI MUST use `@JsonKey(name: 'snake_case_key')` when the API uses snake_case field names.
12
+ - AI MUST keep request and response DTOs as separate classes — never reuse the same model for both.
13
+ - AI MUST keep API DTOs separate from domain models — mapping happens in the service layer.
14
+ - AI MUST catch `DioException` in services and return `Result<T, AppError>` — never let it propagate.
15
+ - AI MUST handle `401` errors in the auth interceptor, not in individual services.
16
+ - AI MUST set `connectTimeout` to 10 seconds and `receiveTimeout` to 30 seconds on the Dio instance.
17
+ Prohibited:
18
+ - AI MUST NOT call Dio or Retrofit clients directly from notifiers or repositories.
19
+ - AI MUST NOT hardcode API base URLs in source code.
20
+ - AI MUST NOT log request bodies, response bodies, or authentication headers.
21
+ - AI MUST NOT use the `http` package directly — always Dio via Retrofit.
22
+ - AI MUST NOT reuse the authenticated Dio instance for auth login/refresh endpoints.
23
+ Patterns:
24
+ - `@RestApi() abstract class ItemsApiClient { factory ItemsApiClient(Dio dio) = _ItemsApiClient; @GET('/api/v1/items') Future<ItemListResponse> getItems(); }`
25
+ - Error mapping: `switch (e.type) { DioExceptionType.badResponse => NetworkError(...), ... }`
26
+ - Auth API: uses `unauthenticatedDioProvider` (no auth interceptor) to avoid refresh loops.
27
+ Examples:
28
+ - `@GET('/api/v1/items/{id}') Future<ItemDto> getItemById(@Path('id') String id);`
29
+ - `@POST('/api/v1/items') Future<ItemDto> createItem(@Body() CreateItemRequest body);`
@@ -0,0 +1,34 @@
1
+ Rule: Enforce Flutter Application Architecture
2
+ Requirements:
3
+ - AI MUST follow this file and all `.ai/rules/*.md` files before generating any code.
4
+ - AI MUST prioritize these rules over default generation behavior.
5
+ - AI MUST use a feature-based, four-layer architecture: Presentation, State (Notifiers), Service, Data (Repositories).
6
+ - AI MUST organize all code under `lib/features/<feature_name>/data/`, `domain/`, and `presentation/` layers.
7
+ - AI MUST keep strict separation: widgets = UI only, notifiers = state only, services = business logic only, repositories = local data only.
8
+ - AI MUST route data flow as: API → Service → Repository (write to Drift) → Drift DB → Repository (read) → Notifier → Widget.
9
+ - AI MUST use Riverpod for all dependency injection — no `new` or static access to services.
10
+ - AI MUST use immutable Freezed models for all domain objects and API DTOs.
11
+ - AI MUST return `Result<T, AppError>` from all service methods that can fail.
12
+ - AI MUST use `BuildContext` only in the presentation layer — never pass it to services or notifiers.
13
+ - AI MUST use the sealed `AppError` hierarchy for all typed error values.
14
+ - AI MUST keep features self-contained — cross-feature communication only through `core/` or `shared/`.
15
+ - AI MUST place infrastructure (AppDatabase, AppLogger, SecureStorageService, Dio) in `core/`.
16
+ - AI MUST co-locate each provider with the class it provides.
17
+ Prohibited:
18
+ - AI MUST NOT bypass these architecture constraints.
19
+ - AI MUST NOT invent alternative architectures, patterns, or folder models.
20
+ - AI MUST NOT place business logic in widgets, screens, or notifiers.
21
+ - AI MUST NOT call APIs directly from repositories or notifiers.
22
+ - AI MUST NOT call Drift DAOs directly from services — always through repositories.
23
+ - AI MUST NOT use global singletons outside of Riverpod.
24
+ - AI MUST NOT use `print()` or `debugPrint()` — always use `AppLogger`.
25
+ - AI MUST NOT allow exceptions to propagate across layer boundaries — wrap them in `Failure`.
26
+ - AI MUST NOT target Flutter web.
27
+ Patterns:
28
+ - Error hierarchy: `sealed class AppError` with `NetworkError`, `AuthError`, `DatabaseError`, `UnknownError`.
29
+ - Result type: `sealed class Result<T>` with `Success<T>(value)` and `Failure<T>(error)`.
30
+ - All models use `@freezed` with `json_serializable`.
31
+ - API DTOs, database rows, and domain models are separate types; mapping happens at service/repository boundary.
32
+ Examples:
33
+ - `return switch (result) { Success(:final value) => value, Failure(:final error) => throw error };`
34
+ - `@Riverpod(keepAlive: true) AppDatabase appDatabase(AppDatabaseRef ref) { ... }`
@@ -0,0 +1,27 @@
1
+ Rule: Enforce Authentication & Token Management
2
+ Requirements:
3
+ - AI MUST store all tokens exclusively in `flutter_secure_storage` via `SecureStorageService`.
4
+ - AI MUST use `encryptedSharedPreferences: true` on Android and `KeychainAccessibility.first_unlock` on iOS.
5
+ - AI MUST provide `SecureStorageService` with `@Riverpod(keepAlive: true)`.
6
+ - AI MUST implement `AuthService` with `login()`, `logout()`, `isAuthenticated()`, and `refreshAccessToken()` methods, each returning `Result<T, AppError>`.
7
+ - AI MUST provide `AuthNotifier` with `@Riverpod(keepAlive: true)` — it must be keepAlive because the GoRouter provider reads it.
8
+ - AI MUST implement the auth interceptor to silently attach the JWT access token to all outgoing requests.
9
+ - AI MUST implement automatic token refresh on `401` in the auth interceptor with a `_isRefreshing` guard.
10
+ - AI MUST use a separate unauthenticated Dio instance for the auth API client (login, refresh, logout endpoints) to avoid infinite refresh loops.
11
+ - AI MUST clear all tokens from secure storage on logout and on failed token refresh.
12
+ - AI MUST check session persistence in `AuthNotifier.build()` by reading from secure storage.
13
+ - AI MUST handle the initial auth check lazily — token validity is confirmed on the first API call, not on startup.
14
+ Prohibited:
15
+ - AI MUST NOT store tokens in SharedPreferences, Drift, plain files, or in-memory objects.
16
+ - AI MUST NOT log tokens, passwords, or credentials under any circumstances.
17
+ - AI MUST NOT include tokens in URL parameters.
18
+ - AI MUST NOT handle `401` errors in services — always in the auth interceptor.
19
+ - AI MUST NOT allow concurrent token refresh attempts — use the `_isRefreshing` flag.
20
+ Patterns:
21
+ - `SecureStorageService` constants: `_accessTokenKey`, `_refreshTokenKey`, `_userIdKey`.
22
+ - On logout: call `storage.clearAll()` even if server logout fails (best-effort).
23
+ - Auth interceptor retry: on successful refresh, retry the original request with the new token; on failed refresh, call `handler.next(err)` and let GoRouter redirect to login.
24
+ - `AuthState` sealed: `authenticated({required User user})` and `unauthenticated()`.
25
+ Examples:
26
+ - `await storage.saveTokens(accessToken: response.accessToken, refreshToken: response.refreshToken);`
27
+ - `options.headers['Authorization'] = 'Bearer $token';`
@@ -0,0 +1,24 @@
1
+ Rule: Enforce Configuration & Secrets Management
2
+ Requirements:
3
+ - AI MUST centralize all configuration in a typed `AppConfig` class in `core/config/app_config.dart`.
4
+ - AI MUST provide `AppConfig` with `@Riverpod(keepAlive: true)`.
5
+ - AI MUST use `String.fromEnvironment(...)` with sensible defaults in `AppConfig.fromEnvironment()`.
6
+ - AI MUST inject all build-time configuration via `--dart-define` variables: `APP_ENV`, `API_BASE_URL`, `APP_VERSION`, `BUILD_NUMBER`.
7
+ - AI MUST support `.dart_define/<env>.json` files via `--dart-define-from-file` for local development.
8
+ - AI MUST exclude `.dart_define/` from version control — commit only a `.dart_define/development.json.example` template.
9
+ - AI MUST store runtime credentials (JWT tokens, user ID) in `flutter_secure_storage` via `SecureStorageService`.
10
+ - AI MUST inject production secrets via CI/CD GitHub Secrets — never commit them.
11
+ - AI MUST expose `isProduction` and `isDebug` convenience getters on `AppConfig`.
12
+ - AI MUST default `API_BASE_URL` to `http://localhost:8787` (local Wrangler worker) in development.
13
+ Prohibited:
14
+ - AI MUST NOT hardcode API URLs, environment flags, or secrets in Dart source code.
15
+ - AI MUST NOT call `String.fromEnvironment(...)` outside of `AppConfig`.
16
+ - AI MUST NOT commit `.dart_define/*.json`, `.env`, or any file containing real secrets.
17
+ - AI MUST NOT store feature flags in compile-time config — they come from the API and are cached in Drift.
18
+ Patterns:
19
+ - Environments: `development`, `staging`, `production` via `AppEnvironment` enum.
20
+ - What goes where: API URL → Dart-define, auth tokens → flutter_secure_storage, feature flags → KV via API cached in Drift.
21
+ - `AppConfig.fromEnvironment()` factory reads all `String.fromEnvironment` calls once at startup.
22
+ Examples:
23
+ - `flutter run --dart-define-from-file=.dart_define/development.json`
24
+ - `flutter build apk --dart-define=APP_ENV=production --dart-define=API_BASE_URL=https://api.myapp.workers.dev`
@@ -0,0 +1,30 @@
1
+ Rule: Enforce Drift SQLite Data Layer
2
+ Requirements:
3
+ - AI MUST use Drift as the only local data storage solution.
4
+ - AI MUST define a single `AppDatabase` class in `core/database/app_database.dart` provided with `@Riverpod(keepAlive: true)`.
5
+ - AI MUST call `ref.onDispose(db.close)` on the AppDatabase provider.
6
+ - AI MUST define all tables as Dart classes extending `Table`, declared in the feature's `data/` folder.
7
+ - AI MUST register all tables and DAOs in the `@DriftDatabase` annotation on `AppDatabase`.
8
+ - AI MUST use `text()` for string primary keys (UUIDs are strings, not integers).
9
+ - AI MUST define explicit `primaryKey` on every table.
10
+ - AI MUST include `isSynced` (BoolColumn), `createdAt` (DateTimeColumn), and `updatedAt` (DateTimeColumn) on all tables that participate in backend sync.
11
+ - AI MUST encapsulate all queries in DAOs — never query tables directly from repositories.
12
+ - AI MUST use `watch()` for reactive queries (UI data sources) and `get()` for one-shot queries (background/sync operations).
13
+ - AI MUST expose `getUnsynced()` and `markSynced()` on any DAO whose table has `isSynced`.
14
+ - AI MUST wrap repositories' mapping so they return typed domain models, not raw Drift rows.
15
+ - AI MUST save new or modified records with `isSynced: false` in the repository.
16
+ - AI MUST increment `schemaVersion` and add an explicit `onUpgrade` migration step for every schema change.
17
+ - AI MUST store all DateTimes in UTC and configure `store_date_time_values_as_text: true` in `build.yaml`.
18
+ - AI MUST use transactions for multi-table write operations.
19
+ - AI MUST add `AppDatabase.inMemory() : super(NativeDatabase.memory());` constructor for testing.
20
+ Prohibited:
21
+ - AI MUST NOT use Hive, shared_preferences, or any other storage library for persistent data.
22
+ - AI MUST NOT query Drift tables directly from services — always through repositories.
23
+ - AI MUST NOT call APIs from repositories.
24
+ - AI MUST NOT modify applied migrations.
25
+ Patterns:
26
+ - Table: `class Items extends Table { TextColumn get id => text()(); BoolColumn get isSynced => boolean().withDefault(const Constant(false))(); @override Set<Column> get primaryKey => {id}; }`
27
+ - DAO reactive: `Stream<List<Item>> watchAll() => (select(items)..orderBy([...])).watch();`
28
+ - DAO upsert: `Future<void> upsert(ItemsCompanion c) => into(items).insertOnConflictUpdate(c);`
29
+ Examples:
30
+ - `@Riverpod(keepAlive: true) AppDatabase appDatabase(AppDatabaseRef ref) { final db = AppDatabase(); ref.onDispose(db.close); return db; }`
@@ -0,0 +1,27 @@
1
+ Rule: Enforce Logging & Diagnostics Standards
2
+ Requirements:
3
+ - AI MUST use the `logger` package wrapped by `AppLogger` for all logging.
4
+ - AI MUST provide `AppLogger` with `@Riverpod(keepAlive: true)` in `core/logging/app_logger.dart`.
5
+ - AI MUST inject `AppLogger` into all services via constructor injection.
6
+ - AI MUST use `logger.debug()` for development diagnostics (disabled in production).
7
+ - AI MUST use `logger.info()` for significant events: login, logout, sync completed, data loaded.
8
+ - AI MUST use `logger.warn()` for recoverable failures: API retry, sync item skipped.
9
+ - AI MUST use `logger.error()` for failures requiring attention: unhandled exceptions, sync aborted.
10
+ - AI MUST set production log level to `Level.warning` — debug and info are suppressed.
11
+ - AI MUST capture uncaught Flutter errors in `FlutterError.onError` in `main.dart`.
12
+ - AI MUST capture async errors in `PlatformDispatcher.instance.onError` in `main.dart`.
13
+ - AI MUST always log: auth events, sync operations, feature-level operations, error conditions.
14
+ - AI MUST include contextual key-value pairs in log messages using the `extra` parameter.
15
+ Prohibited:
16
+ - AI MUST NOT use `print()` or `debugPrint()` in any production code.
17
+ - AI MUST NOT use the `logger` package directly in features — always through `AppLogger`.
18
+ - AI MUST NOT log passwords, tokens, credentials, PII (email, name, phone), raw API bodies, or payment information.
19
+ Patterns:
20
+ - Log format: `logger.info('Items fetched', extra: {'count': response.items.length});`
21
+ - Error log: `logger.error('Sync failed', error: e, stackTrace: st);`
22
+ - Warn log: `logger.warn('Failed to push item', error: e.message, extra: {'itemId': item.id});`
23
+ - Production output: route `Level.warning` and above to Sentry or platform crash reporting.
24
+ - Message tense: present for actions (`'Fetching items'`), past for completed events (`'Items loaded'`).
25
+ Examples:
26
+ - `logger.info('User login successful', extra: {'userId': userId});`
27
+ - `logger.warn('Sync failed for item', extra: {'itemId': itemId});`
@@ -0,0 +1,28 @@
1
+ Rule: Enforce GoRouter Navigation
2
+ Requirements:
3
+ - AI MUST use GoRouter for all navigation.
4
+ - AI MUST configure the router in `core/router/app_router.dart` as a `@Riverpod(keepAlive: true)` provider.
5
+ - AI MUST define all route name constants in `abstract final class AppRoutes` using kebab-case strings.
6
+ - AI MUST navigate using `context.goNamed(AppRoutes.routeName)` — never hardcoded path strings.
7
+ - AI MUST use `context.goNamed` for top-level navigation (replaces current route).
8
+ - AI MUST use `context.pushNamed` for stacked/modal navigation.
9
+ - AI MUST use `context.pop()` to navigate back.
10
+ - AI MUST implement all auth guards in the router's `redirect` callback — never in individual screens.
11
+ - AI MUST use `ShellRoute` for persistent navigation UI (bottom nav, side drawer).
12
+ - AI MUST pass only primitive IDs through path parameters, not full objects.
13
+ - AI MUST load data inside the destination screen using the ID via Riverpod providers.
14
+ - AI MUST define a custom `errorBuilder` for unmatched routes.
15
+ - AI MUST configure deep links per platform (intent filters on Android, URL schemes on iOS/macOS).
16
+ Prohibited:
17
+ - AI MUST NOT use hardcoded path strings in navigation calls.
18
+ - AI MUST NOT check auth state inside individual screens to redirect.
19
+ - AI MUST NOT pass complex objects through GoRouter's `extra` parameter.
20
+ - AI MUST NOT use the imperative `Navigator` API — always GoRouter.
21
+ Patterns:
22
+ - Router provider: `@Riverpod(keepAlive: true) GoRouter router(RouterRef ref) { final authState = ref.watch(authNotifierProvider); return GoRouter(redirect: ..., routes: _routes); }`
23
+ - Route constant: `static const itemDetail = 'item-detail';`
24
+ - Navigation: `context.goNamed(AppRoutes.itemDetail, pathParameters: {'id': item.id});`
25
+ - Redirect: `if (!isLoggedIn && !isAuthRoute) return '/auth/login'; if (isLoggedIn && isAuthRoute) return '/dashboard'; return null;`
26
+ Examples:
27
+ - `context.goNamed(AppRoutes.dashboard);`
28
+ - `context.goNamed(AppRoutes.itemDetail, pathParameters: {'id': item.id});`
@@ -0,0 +1,26 @@
1
+ Rule: Enforce Offline-First & Background Sync
2
+ Requirements:
3
+ - AI MUST treat the local Drift database as the primary data source at all times — the UI never reads from the API directly.
4
+ - AI MUST use `connectivity_plus` via a `ConnectivityService` provided with `@Riverpod(keepAlive: true)`.
5
+ - AI MUST implement a `SyncService` provided with `@Riverpod(keepAlive: true)` that listens to `ConnectivityService.isOnlineStream` and triggers `syncAll()` when the device comes back online.
6
+ - AI MUST guard `syncAll()` with a `_isSyncing` boolean to prevent concurrent sync runs.
7
+ - AI MUST implement a dedicated sync task class per resource (e.g., `ItemSyncTask`) that pushes local unsynced changes then pulls remote data.
8
+ - AI MUST push local unsynced items before pulling remote data in every sync task.
9
+ - AI MUST handle individual record push failures gracefully — log the failure and continue syncing other records.
10
+ - AI MUST use upsert semantics when writing pulled data to Drift (server wins on conflict).
11
+ - AI MUST save offline writes locally with `isSynced: false` immediately, then attempt an immediate push if online.
12
+ - AI MUST support pull-to-refresh by calling `syncService.syncAll()` from the UI.
13
+ - AI MUST implement `SyncStatusNotifier` (keepAlive) with sealed states: `idle`, `syncing`, `lastSyncedAt`, `error`.
14
+ - AI MUST perform an initial sync on first launch before navigating to the main content.
15
+ - AI MUST log sync start, completion, and any failures using `AppLogger`.
16
+ Prohibited:
17
+ - AI MUST NOT read from the API in the UI layer — always from Drift streams via notifiers.
18
+ - AI MUST NOT allow a single sync failure to abort the entire sync run.
19
+ - AI MUST NOT implement complex merge conflict strategies — server wins is the default.
20
+ Patterns:
21
+ - Sync task: `async execute() { await _pushLocalChanges(); await _pullRemoteData(); }`
22
+ - Push: iterate `getUnsynced()`, call API per item, call `markSynced([id])` on success.
23
+ - Pull: call API list endpoint, call `repository.saveAll(items)` with upsert.
24
+ - Offline write: `await _repository.save(item); if (await _connectivity.isOnline) { ... markSynced; }`
25
+ Examples:
26
+ - `_connectivitySubscription = connectivity.isOnlineStream.listen((isOnline) { if (isOnline && !_isSyncing) syncAll(); });`
@@ -0,0 +1,30 @@
1
+ Rule: Enforce Platform Targets & Build Configuration
2
+ Requirements:
3
+ - AI MUST target iOS (min 16.0), Android (min API 26), macOS (min 13.0), and Windows (min 10) only.
4
+ - AI MUST manage environments (development, staging, production) via Dart-define variables, not Flutter flavors.
5
+ - AI MUST pin all dependencies to major versions in `pubspec.yaml` (e.g., `^2.x.x`).
6
+ - AI MUST commit `pubspec.lock` to ensure reproducible builds.
7
+ - AI MUST use GitHub Actions for all CI/CD pipelines.
8
+ - AI MUST run `dart run build_runner build --delete-conflicting-outputs` in every CI run before analyze and test.
9
+ - AI MUST enforce the branch model: `main` = production, `staging` = staging, `feature/*` = development.
10
+ - AI MUST require all PRs to pass `flutter analyze` and `flutter test --coverage` before merge.
11
+ - AI MUST manage signing credentials exclusively via GitHub Secrets — never commit keystores, `.p12` files, or `key.properties`.
12
+ - AI MUST enable Keychain sharing on iOS and the appropriate entitlements on macOS for `flutter_secure_storage`.
13
+ - AI MUST configure Associated Domains on iOS and intent filters on Android for deep link support.
14
+ - AI MUST encapsulate all platform-conditional code in dedicated platform service classes.
15
+ - AI MUST pin the Flutter version in `.flutter-version` or the CI workflow YAML.
16
+ Prohibited:
17
+ - AI MUST NOT target Flutter web — use Nuxt + Cloudflare for web interfaces.
18
+ - AI MUST NOT use Flutter flavors for environment management — Dart-define is the standard.
19
+ - AI MUST NOT commit signing credentials, keystores, provisioning profiles, or `key.properties`.
20
+ - AI MUST NOT scatter `Platform.isIOS` / `Platform.isAndroid` checks in widget trees.
21
+ - AI MUST NOT run `flutter pub upgrade` as part of routine development — only deliberately.
22
+ - AI MUST NOT allow direct commits to `main` — all changes enter via pull request.
23
+ Patterns:
24
+ - CI validate: checkout → Flutter setup → `pub get` → `build_runner` → `flutter analyze` → `flutter test`.
25
+ - Platform CI secrets (Android): `ANDROID_KEYSTORE_BASE64`, `ANDROID_KEY_PROPERTIES`, `GOOGLE_PLAY_SERVICE_ACCOUNT`.
26
+ - Platform CI secrets (iOS): `IOS_CERTIFICATE_BASE64`, `IOS_CERTIFICATE_PASSWORD`, `IOS_PROVISIONING_PROFILE_BASE64`, `APP_STORE_CONNECT_API_KEY`.
27
+ - Shared CI secrets: `PROD_API_BASE_URL`, `STAGING_API_BASE_URL`, `APP_VERSION`.
28
+ Examples:
29
+ - `flutter build appbundle --release --dart-define=APP_ENV=production --dart-define=API_BASE_URL=$API_BASE_URL`
30
+ - `flutter build ipa --release --dart-define=APP_ENV=production --export-options-plist=ios/ExportOptions.plist`
@@ -0,0 +1,32 @@
1
+ Rule: Enforce Standard Project Structure
2
+ Requirements:
3
+ - AI MUST place all application source code under `lib/`.
4
+ - AI MUST use the standard top-level layout: `lib/main.dart`, `lib/app.dart`, `lib/core/`, `lib/features/`, `lib/shared/`.
5
+ - AI MUST place infrastructure in `core/`: `bootstrap/`, `database/`, `network/`, `router/`, `storage/`, `logging/`, `errors/`, `config/`, `theme/`.
6
+ - AI MUST place each feature under `lib/features/<feature_name>/` with `data/`, `domain/`, and `presentation/` subdirectories.
7
+ - AI MUST place reusable cross-feature widgets and utilities under `lib/shared/widgets/` and `lib/shared/extensions/`.
8
+ - AI MUST mirror the `lib/features/` structure in `test/features/`.
9
+ - AI MUST place test fixtures in `test/helpers/fixtures/`.
10
+ - AI MUST place AI rule files in `.ai/rules/`.
11
+ - AI MUST follow naming conventions: snake_case files, PascalCase classes, camelCase variables and constants.
12
+ - AI MUST suffix: screens with `Screen`, notifiers with `Notifier`, repositories with `Repository`, services with `Service`.
13
+ - AI MUST suffix Riverpod providers as camelCase + `Provider` (e.g., `authServiceProvider`).
14
+ - AI MUST keep `main.dart` minimal — only Flutter binding init, bootstrap, and `runApp`.
15
+ - AI MUST declare all assets in `pubspec.yaml`.
16
+ - AI MUST commit `pubspec.lock`.
17
+ Prohibited:
18
+ - AI MUST NOT create feature-specific logic inside `core/` or `shared/`.
19
+ - AI MUST NOT create centralized provider files — providers live with the class they provide.
20
+ - AI MUST NOT scatter `Platform.isIOS` checks throughout widget trees.
21
+ - AI MUST NOT use callbacks for `async` operations — always use `async/await`.
22
+ - AI MUST NOT commit `.dart_define/` files, `.g.dart`, or `.freezed.dart` files.
23
+ Patterns:
24
+ - `lib/features/auth/data/auth_repository.dart`
25
+ - `lib/features/auth/domain/auth_service.dart`
26
+ - `lib/features/auth/presentation/screens/login_screen.dart`
27
+ - `lib/features/auth/presentation/notifiers/auth_notifier.dart`
28
+ - `lib/core/database/app_database.dart`
29
+ - `lib/core/network/dio_client.dart`
30
+ Examples:
31
+ - File: `auth_service.dart` → Class: `AuthService` → Provider: `authServiceProvider`
32
+ - File: `item_list_screen.dart` → Class: `ItemListScreen`
@@ -0,0 +1,32 @@
1
+ Rule: Enforce Riverpod State Management
2
+ Requirements:
3
+ - AI MUST use Riverpod with `riverpod_generator` for all state management and dependency injection.
4
+ - AI MUST wrap the root widget in `ProviderScope` exactly once in `main.dart`.
5
+ - AI MUST use `@riverpod` annotation on functions for services, repositories, and API clients.
6
+ - AI MUST use `@riverpod` class notation (extending `_$ClassName`) for mutable notifiers.
7
+ - AI MUST use `@Riverpod(keepAlive: true)` for: AppDatabase, SecureStorageService, AppLogger, Dio client, AuthNotifier, router, ConnectivityService, SyncService.
8
+ - AI MUST use auto-dispose (default `@riverpod`) for feature services, feature notifiers, and screen-specific state.
9
+ - AI MUST use `ref.watch(provider)` only inside `build()` methods.
10
+ - AI MUST use `ref.read(provider)` only inside callbacks, event handlers, and notifier methods.
11
+ - AI MUST use `ref.listen(provider, ...)` for one-off side effects like navigation and snackbars.
12
+ - AI MUST use `AsyncValue` with `.when()` for all async state in the UI.
13
+ - AI MUST define complex notifier state as `@freezed sealed class` for exhaustive pattern matching.
14
+ - AI MUST use `family` modifier for providers that require parameters.
15
+ - AI MUST use `StreamNotifier` when the data source is a Drift reactive stream.
16
+ - AI MUST add `part 'filename.g.dart';` and import `riverpod_annotation` in annotated files.
17
+ Prohibited:
18
+ - AI MUST NOT write providers manually using `Provider(...)`, `StateNotifierProvider(...)`, or `ChangeNotifierProvider(...)`.
19
+ - AI MUST NOT create global mutable singletons outside of Riverpod.
20
+ - AI MUST NOT pass `WidgetRef` to services, repositories, or notifier constructors.
21
+ - AI MUST NOT use `ref.read` inside `build()`.
22
+ - AI MUST NOT use `ref.watch` inside callbacks or notifier methods.
23
+ - AI MUST NOT check `.isLoading` or `.hasError` directly — always use `.when()` or `.maybeWhen()`.
24
+ - AI MUST NOT create centralized provider files.
25
+ Patterns:
26
+ - Function provider: `@riverpod AuthService authService(AuthServiceRef ref) => AuthService(...);`
27
+ - Notifier: `@riverpod class AuthNotifier extends _$AuthNotifier { @override FutureOr<AuthState> build() async { ... } }`
28
+ - StreamNotifier: `@riverpod class ItemListNotifier extends _$ItemListNotifier { @override Stream<List<Item>> build() => ref.read(itemRepositoryProvider).watchAll(); }`
29
+ - Family: `@riverpod Future<ItemDetail> itemDetail(ItemDetailRef ref, String itemId) async { ... }`
30
+ Examples:
31
+ - `final state = ref.watch(itemListNotifierProvider);`
32
+ - `state.when(loading: () => LoadingIndicator(), error: (e, _) => ErrorView(error: e.toString()), data: (items) => ItemList(items: items))`
@@ -0,0 +1,31 @@
1
+ Rule: Enforce Testing Standards
2
+ Requirements:
3
+ - AI MUST write tests before implementation (TDD).
4
+ - AI MUST write unit tests for every service method, notifier state transition, and repository operation.
5
+ - AI MUST use `mocktail` for mocking — never `mockito` with code generation.
6
+ - AI MUST use `ProviderContainer` with provider overrides to test notifiers without a widget tree.
7
+ - AI MUST use `AppDatabase.inMemory()` for repository tests — never a real database file.
8
+ - AI MUST call `addTearDown(container.dispose)` in every notifier test `setUp`.
9
+ - AI MUST call `tearDown(() => db.close())` in every repository test.
10
+ - AI MUST structure each test using Arrange / Act / Assert.
11
+ - AI MUST use `group()` to organize related tests within a test file.
12
+ - AI MUST name tests descriptively: `'returns items when cache is populated'`.
13
+ - AI MUST place reusable test data in `test/helpers/fixtures/<feature>_fixtures.dart` as `abstract final class`.
14
+ - AI MUST place mock class declarations in `test/helpers/mock_providers.dart`.
15
+ - AI MUST configure mock logger stubs in `setUp` to silence logging during tests.
16
+ - AI MUST test widget screens by overriding providers in a wrapping `ProviderScope`.
17
+ - AI MUST ensure `flutter test --coverage` passes in CI before any PR merges.
18
+ Prohibited:
19
+ - AI MUST NOT use real service implementations in unit tests — always mocks.
20
+ - AI MUST NOT use `mockito` or its code generation in this project.
21
+ - AI MUST NOT write tests that depend on execution order.
22
+ - AI MUST NOT skip tests or mark them as `skip` without an explicit reason.
23
+ Patterns:
24
+ - Mock declaration: `class MockItemService extends Mock implements ItemService {}`
25
+ - ProviderContainer: `container = ProviderContainer(overrides: [itemServiceProvider.overrideWithValue(mockService)]);`
26
+ - Notifier test: `final state = await container.read(itemListNotifierProvider.future);`
27
+ - Widget test: `await tester.pumpWidget(ProviderScope(overrides: [...], child: const MaterialApp(home: ItemListScreen())));`
28
+ - Fixture: `abstract final class ItemFixtures { static final item1 = Item(id: 'item-001', title: 'First Item', ...); }`
29
+ Examples:
30
+ - `when(() => mockService.getItems()).thenAnswer((_) async => Success(items));`
31
+ - `verify(() => mockApi.getItems()).called(1);`
@@ -0,0 +1,31 @@
1
+ # Architecture Principles
2
+
3
+ ## Core Standards
4
+ - Use one technology stack across all projects: Nuxt 4 + Cloudflare + D1 + Drizzle
5
+ - Maintain one repository per project
6
+ - Configure one database per environment
7
+ - Implement a mandatory services layer for all business logic
8
+ - Generate migrations for every schema change
9
+ - Write tests from day one
10
+ - Deploy using Cloudflare-first architecture
11
+ - Optimize only when measurements justify the need
12
+
13
+ ## Philosophy
14
+ - Prioritize mastery over novelty
15
+ - Choose consistency over experimentation
16
+ - Focus on shipping over theorizing
17
+ - Maintain discipline over chaos
18
+
19
+ ## Application Architecture
20
+ - Use Nuxt as a fullstack framework with `/app` for UI and `/server` for backend
21
+ - Keep API routes thin; business logic belongs in services
22
+ - Access databases only from within service layer
23
+ - Never place business logic in API handlers
24
+ - Never make direct database calls from API files
25
+
26
+ ## When NOT to Use This Stack
27
+ Avoid this architecture when:
28
+ - Complex relational requirements exceed SQLite capabilities
29
+ - Extreme realtime multiplayer scale is required
30
+ - Long-running CPU-intensive workloads are needed
31
+ - On-premise deployment is required
@@ -0,0 +1,35 @@
1
+ # Authentication Standards
2
+
3
+ ## Choose Authentication Model Based on Project Type
4
+
5
+ ### Internal Applications
6
+ - Use OAuth with Entra / Azure AD
7
+ - Validate JWT in server middleware
8
+ - Map role claims server-side
9
+ - Extract roles from JWT token claims
10
+
11
+ ### Public SaaS Applications
12
+ - Implement OAuth (Google, GitHub) as primary method
13
+ - Optionally support email/password authentication
14
+ - Use HTTP-only cookies for session management
15
+ - Store sessions in D1 database
16
+ - Optionally cache sessions in KV for performance
17
+
18
+ ### Mobile Backends
19
+ - Issue short-lived JWT access tokens (15 minutes recommended)
20
+ - Store refresh tokens in D1 database
21
+ - Implement stateless token validation
22
+ - Never store tokens in frontend local storage
23
+
24
+ ## Global Authentication Rules
25
+ - Implement no role logic in frontend code
26
+ - Enforce all authorization checks server-side
27
+ - Centralize authentication in middleware
28
+ - Never trust client-side authentication state
29
+ - Always validate tokens on every protected request
30
+
31
+ ## Middleware Implementation
32
+ - Create centralized auth middleware at `/server/middleware/auth.ts`
33
+ - Return 401 for missing or invalid tokens
34
+ - Attach user context to request event for downstream use
35
+ - Log authentication failures for security monitoring