Skip to content

fix: harden deploy pre-rollout DB drift guardrails - #197

Merged
LucasSantana-Dev merged 3 commits into
mainfrom
fix/deploy-db-drift-guardrails
Mar 13, 2026
Merged

LucasSantana-Dev merged 3 commits into
mainfrom
fix/deploy-db-drift-guardrails

Conversation

@LucasSantana-Dev

@LucasSantana-Dev LucasSantana-Dev commented Mar 13, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • add a shared required-database-relation guard used by backend startup and deploy preflight
  • expand required sentinel relation checks to cover automation tables plus guild_role_grants
  • harden deploy pre-rollout DB gates with prisma migrate status before service restart
  • classify deploy DB guard failures with explicit migration/schema drift logs
  • document deploy DB preconditions in CI/CD docs and changelog

Verification

  • npm run test --workspace=packages/backend -- tests/unit/startup/requiredDatabaseRelations.test.ts tests/unit/startup/verifyRequiredDatabaseState.test.ts tests/unit/bootstrap.test.ts
  • bash -n scripts/deploy.sh

Notes

  • npm run type:check --workspace=packages/shared and npm run type:check --workspace=packages/backend still hit existing baseline failures in this repo (generated Prisma + pre-existing strict typing issues outside this change scope).

Summary by CodeRabbit

  • Infrastructure
    • Added database validation checks during deployment that verify all required database state before services restart
    • Deployment now fails if database migrations are incomplete or schema inconsistencies are detected, preventing rollout with invalid database state
    • System enforces database preflight validation to catch issues early and maintain consistency

@vercel

vercel Bot commented Mar 13, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lucky Ready Ready Preview, Comment Mar 13, 2026 2:56pm

Request Review

@netlify

netlify Bot commented Mar 13, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for regal-bunny-0c8efe ready!

Name Link
🔨 Latest commit 238ca88
🔍 Latest deploy log https://app.netlify.com/projects/regal-bunny-0c8efe/deploys/69b42574de7fe4000847ad1c
😎 Deploy Preview https://deploy-preview-197--regal-bunny-0c8efe.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai

coderabbitai Bot commented Mar 13, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@LucasSantana-Dev has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 11 minutes and 56 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 399f7ba9-01e9-42b4-b6b2-aeec81d0fc88

📥 Commits

Reviewing files that changed from the base of the PR and between f0a1ed7 and 238ca88.

📒 Files selected for processing (1)
  • packages/shared/src/utils/requiredDatabaseRelations.ts
📝 Walkthrough

Walkthrough

Adds a shared database relations verifier used during deploy-time validation. Requires prisma migrate status check before service restart. Enforces verification of four required database tables (guild_role_grants, guild_automation_manifests, guild_automation_runs, guild_automation_drifts). Unifies verification logic and strengthens pre-flight deployment validation.

Changes

Cohort / File(s) Summary
Core Database Verification Utility
packages/shared/src/utils/requiredDatabaseRelations.ts, packages/shared/src/utils/index.ts
New utility module implementing verifyRequiredDatabaseRelations function with type-safe Prisma delegates. Checks four required database relations, catches P2021 errors to surface startup errors with ERR_DB_SCHEMA_MISSING code, and exports REQUIRED_DATABASE_RELATIONS constant. Re-exported from shared utils index.
Startup Verification Refactoring
packages/backend/src/startup/verifyRequiredDatabaseState.ts
Simplified startup verification to delegate to verifyRequiredDatabaseRelations instead of inline Prisma queries. Reduces implementation from 30 to 2 lines while maintaining Promise contract.
Unit Tests
packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts, packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
New test suite (131 lines) covering healthy schema, missing relations per table, and non-P2021 error handling. Updated existing tests (22/-39 lines) to mock verifyRequiredDatabaseRelations and validate delegation behavior.
Deploy Script
scripts/deploy.sh
Enhanced deploy workflow with prisma migrate status check, new Node-based relation guard script execution inside backend container, and improved error logging/notification for migration and schema validation failures.
Documentation & Changelog
docs/CI_CD.md, CHANGELOG.md
Added deploy preflight check documentation detailing database preconditions (running migrations, checking status, verifying relation guards) and failure behavior. Updated changelog with guardrail summary.

Sequence Diagram

sequenceDiagram
    participant Deploy as Deploy Script
    participant Prisma as Prisma Migrate
    participant DB as Database
    participant Guard as Relation Guard
    participant Services as Runtime Services
    participant Notify as Notification

    Deploy->>Prisma: prisma migrate deploy
    Prisma->>DB: Apply pending migrations
    DB-->>Prisma: Done
    Prisma-->>Deploy: Success

    Deploy->>Prisma: prisma migrate status
    Prisma->>DB: Check migration status
    DB-->>Prisma: Status
    Prisma-->>Deploy: Status report

    alt Migration status check fails
        Deploy->>Notify: Send migration error
        Notify-->>Deploy: Notified
        Deploy->>Deploy: Exit with error
    end

    Deploy->>Guard: Execute relation guard script
    Guard->>DB: Check guild_role_grants
    Guard->>DB: Check guild_automation_manifests
    Guard->>DB: Check guild_automation_runs
    Guard->>DB: Check guild_automation_drifts
    DB-->>Guard: All relations exist

    alt Any relation missing
        Guard->>Guard: Catch P2021 error
        Guard->>Deploy: Exit with ERR_DB_SCHEMA_MISSING
        Deploy->>Notify: Send schema error
        Notify-->>Deploy: Notified
    else All relations verified
        Guard-->>Deploy: Success
        Deploy->>Services: Restart runtime services
        Services-->>Deploy: Restarted
        Deploy->>Notify: Send success
        Notify-->>Deploy: Notified
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

size/m

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: harden deploy pre-rollout DB drift guardrails' accurately summarizes the main change: strengthening database validation checks before deployment rollout.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/deploy-db-drift-guardrails
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot added the size/m label Mar 13, 2026
coderabbitai[bot]
coderabbitai Bot previously requested changes Mar 13, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/shared/src/utils/requiredDatabaseRelations.ts`:
- Around line 54-57: Replace the unsafe double-cast on getPrismaClient() in the
verifyRequiredDatabaseRelations default parameter by removing the "as unknown as
RequiredDatabaseStatePrisma" cast and instead define RequiredDatabaseStatePrisma
as a structural type using Pick from the Prisma client (i.e., Pick<PrismaClient,
'modelA' | 'modelB' ...> matching only the models used in this module), then
change the default parameter to call getPrismaClient() directly; update any
import/alias so verifyRequiredDatabaseRelations, RequiredDatabaseStatePrisma,
and getPrismaClient are consistent and type-safe without manual casts.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 158cb2b6-a7a0-4a04-9bea-a739b00ac9c5

📥 Commits

Reviewing files that changed from the base of the PR and between 563b263 and f0a1ed7.

📒 Files selected for processing (8)
  • CHANGELOG.md
  • docs/CI_CD.md
  • packages/backend/src/startup/verifyRequiredDatabaseState.ts
  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
  • packages/shared/src/utils/index.ts
  • packages/shared/src/utils/requiredDatabaseRelations.ts
  • scripts/deploy.sh
📜 Review details
🧰 Additional context used
📓 Path-based instructions (28)
**/*.{js,jsx,ts,tsx,vue,html}

📄 CodeRabbit inference engine (.cursor/rules/accessibility-openness.mdc)

Provide accessible UI components using semantic HTML and ARIA attributes where necessary

Files:

  • packages/backend/src/startup/verifyRequiredDatabaseState.ts
  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/shared/src/utils/requiredDatabaseRelations.ts
  • packages/shared/src/utils/index.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/dependency-injection.mdc)

**/*.{ts,tsx,js,jsx}: Prefer constructor injection for classes that require dependencies
Avoid global mutable singletons unless necessary
Use explicit interfaces for external dependencies to make testing easier

**/*.{ts,tsx,js,jsx}: Include required references in PRs/code for non-trivial logic: TypeScript (official docs), MDN (JavaScript reference), and official docs for any runtime/framework/libraries used (e.g., Node.js, React) as applicable.
Before assuming behavior of an API, include the doc link and a ≤25-word quote when the change relies on it.

**/*.{ts,tsx,js,jsx}: Prefer named exports for clear usage and easier refactors in TypeScript/JavaScript
Keep import order consistent: external first, then internal modules
Remove dead code and unused imports

**/*.{ts,tsx,js,jsx}: Use PascalCase naming convention for React/UI components
Use camelCase naming convention for variables and functions
Use UPPER_SNAKE_CASE naming convention for constants
Maintain consistent import grouping and ordering within the project, keeping third-party imports separate from local imports
For external data sources (HTTP, database), always validate and sanitize input using type guards or schema validators

**/*.{ts,tsx,js,jsx}: Use Prettier with no semicolons, single quotes, 4-space indent, 80 character width
Files must not exceed 250 lines and this is enforced

Implement TypeScript typecheck and linter in CI quality checks

**/*.{ts,tsx,js,jsx}: Use TypeScript for enhanced type safety
Implement error handling and error logging
Avoid commenting code unless extremely necessary - code should explain itself with descriptive names
Leave NO todos, placeholders or missing pieces in the code
Variables and functions must use camelCase
Constants must use UPPER_SNAKE_CASE
Use arrow functions for methods and computed properties
Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements
Maintain consistent import grouping/order: external imports first, then...

Files:

  • packages/backend/src/startup/verifyRequiredDatabaseState.ts
  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/shared/src/utils/requiredDatabaseRelations.ts
  • packages/shared/src/utils/index.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/error-handling.mdc)

**/*.{js,jsx,ts,tsx}: Never throw strings. Throw Error (or typed subclasses) with descriptive messages
Include causal error as cause when available for better debugging
Define clear, stable error codes (e.g., ERR_AUTH_EXPIRED, ERR_NETWORK_TIMEOUT)
Provide optional metadata (e.g., details, retryable, status, correlationId) in error objects
Use domain error classes per area (e.g., AuthenticationError, ValidationError, NetworkError)
Log errors with structure (message, code, stack, cause, correlationId, user context where appropriate)
Mark retryable vs nonRetryable errors where helpful for operations
Set timeouts and handle aborts/cancellations; avoid dangling requests in API/network code
Implement backoff for transient failures; avoid infinite retries
Map HTTP status → domain errors; 4xx vs 5xx behave differently (e.g., retry for 5xx/network)

**/*.{js,jsx,ts,tsx}: Use functional components with hooks in React/React Native. Avoid class components.
Keep components focused on a single responsibility; extract complex logic into custom hooks.
Keep state local when possible. Use Context/Zustand/Redux only when necessary for state management.
If props or state traverse more than 3 levels, consider using context or a feature-scoped store instead of prop drilling.
Use performance optimization techniques: React.memo, useMemo, useCallback, Suspense (web), and virtualization for long lists; avoid unnecessary re-renders.
Web accessibility: use semantic HTML, labels, focus management, keyboard navigation, and aria-* attributes as needed.
React Native accessibility: use accessibility props (accessible, accessibilityLabel), proper roles and labels.
Identify and extract repetitive UI components proactively to components/ with clear props and minimal coupling.
Web styles: prefer co-located styles or design system tokens; avoid global style leakage.
React Native styles: prefer StyleSheet.create, design tokens, and theme providers; avoid in...

Files:

  • packages/backend/src/startup/verifyRequiredDatabaseState.ts
  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/shared/src/utils/requiredDatabaseRelations.ts
  • packages/shared/src/utils/index.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

Introduce interfaces at module boundaries to enable testing and substitutions

**/*.{ts,tsx}: Avoid using any type in TypeScript. If unavoidable, use unknown with type guards and justify with a code comment
Prefer interface for defining public object shapes in TypeScript, use type for unions and utility types
Use TypeScript utility types such as Partial, Pick, Omit, Readonly, and Record when appropriate
Use I{Name} naming convention for interfaces in TypeScript
Use T{Name} naming convention for type aliases and utility types in TypeScript

**/*.{ts,tsx}: Functions must be less than 50 lines with cyclomatic complexity less than 10
Do not use any types - ESLint enforces this at error level

**/*.{ts,tsx}: Prefer types over interfaces for most cases
Don't ever use any - type safety always
Avoid enums; use const objects instead
For complex types, create a separate file to declare them and import them
Avoid using any type; if unavoidable, use unknown with type guards and justify with code comment
Prefer interface for public API shapes; use type for unions and utility types
Use TypeScript utility types (Partial, Pick, Omit, Readonly, Record)

Files:

  • packages/backend/src/startup/verifyRequiredDatabaseState.ts
  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/shared/src/utils/requiredDatabaseRelations.ts
  • packages/shared/src/utils/index.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
packages/backend/src/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

packages/backend/src/**/*.ts: Validation must use Zod schemas in backend/src/schemas/ and be applied via validateBody, validateParams, or validateQuery
Do not reassign req.query in Express middleware - it is read-only in Express 5

Files:

  • packages/backend/src/startup/verifyRequiredDatabaseState.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/documentation.mdc)

**/*.{js,ts,tsx,jsx}: Minimize comments in code; explain the 'why' when non-obvious, let code express the 'what' through clear naming
Document trade-offs briefly when deviating from ideal patterns

**/*.{js,ts,tsx,jsx}: Store secrets, ports, and hosts in environment variables (.env, .env.example) and never hardcode them
Avoid redundant or decorative AI comments; code should be self-explanatory and only commented when logic is non-obvious; prefer refactoring over lengthy comments

Files:

  • packages/backend/src/startup/verifyRequiredDatabaseState.ts
  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/shared/src/utils/requiredDatabaseRelations.ts
  • packages/shared/src/utils/index.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
packages/backend/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-backend-api.mdc)

packages/backend/src/**/*.{ts,tsx}: Use shared config and env from @lucky/shared when needed; avoid duplicating env parsing in backend code
Keep tokens and secrets in environment variables only; never hardcode or expose in code

Files:

  • packages/backend/src/startup/verifyRequiredDatabaseState.ts
packages/backend/**

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

The backend package depends on shared and contains Express API with auth and guild routes

Files:

  • packages/backend/src/startup/verifyRequiredDatabaseState.ts
  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
**/*.{js,mjs,ts,mts}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Use Node.js version ≥22 with ESM (ECMAScript modules) only; no CommonJS

Files:

  • packages/backend/src/startup/verifyRequiredDatabaseState.ts
  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/shared/src/utils/requiredDatabaseRelations.ts
  • packages/shared/src/utils/index.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
packages/backend/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-backend.mdc)

packages/backend/**/*.ts: Apply .cursor/rules/lucky-backend-api.mdc for structure and conventions when acting as backend specialist
Use .cursor/skills/backend-express/SKILL.md for Express routes, middleware, and services when acting as backend specialist
Use @lucky/shared for config and DB/Redis when needed in backend code

Files:

  • packages/backend/src/startup/verifyRequiredDatabaseState.ts
  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
**/docs/**/*.{md,mdx}

📄 CodeRabbit inference engine (.cursor/rules/documentation.mdc)

**/docs/**/*.{md,mdx}: Keep API documentation in sync with code changes
Document significant architectural design choices

Files:

  • docs/CI_CD.md
{CHANGELOG.md,docs/**}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Update CHANGELOG.md and relevant docs/ files when behavior or setup changes

Files:

  • docs/CI_CD.md
  • CHANGELOG.md
**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/frontend.mdc)

**/*.{test,spec}.{js,jsx,ts,tsx}: Test behavior, not implementation. Prefer Testing Library utilities for testing React/React Native components.
For React Native tests: mock native modules and test component interactions and accessibility labels.

Files:

  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

**/*.{test,spec}.{ts,tsx,js,jsx}: Test behavior, not implementation details
Prefer unit tests for core logic; add integration tests at meaningful boundaries

Files:

  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
**/*.{test,spec}.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/testing-quality.mdc)

**/*.{test,spec}.{js,ts,jsx,tsx}: Use Jest + a React testing library for unit and component tests as applicable
Test behavior, not implementation details

Files:

  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
packages/backend/tests/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-backend-api.mdc)

Organize tests in packages/backend/tests/ with unit tests under unit/ and integration tests under integration/, following existing patterns with fixtures and setup

Files:

  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
{packages/*/tests/**/*.test.{js,ts},tests/**/*.test.{js,ts}}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Add or adjust unit and integration tests when changing behavior; follow existing patterns in packages/*/tests and root tests/ directories

Files:

  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
**/*.{spec,test}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/quality.mdc)

**/*.{spec,test}.{ts,tsx,js,jsx}: Use Jest for unit and integration tests
Test behavior, not implementation details
Run unit, integration tests, and coverage report in CI quality checks

Files:

  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
packages/backend/tests/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-backend.mdc)

Follow existing patterns for unit and integration tests in packages/backend/tests/

Files:

  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
{packages/shared/**,prisma/**}/**/*.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Use Prisma for PostgreSQL database and Redis for caching with shared client configuration

Files:

  • packages/shared/src/utils/requiredDatabaseRelations.ts
  • packages/shared/src/utils/index.ts
packages/shared/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/lucky-shared.mdc)

packages/shared/**/*.ts: Organize the Lucky Shared Package with the following directory structure: Config in packages/shared/src/config/ (environment, constants, feature toggles, YouTube config); Services in packages/shared/src/services/ (DatabaseService, Redis client/operations, FeatureToggleService, ReactionRoles, RoleManagement); Types in packages/shared/src/types/ (errors, commands, common, discord, music); Utils in packages/shared/src/utils/ (error handling, retry, embeds, log, monitoring, composables, prismaClient)
Do not add dependencies on bot or backend packages; shared is the foundational package used by both
Use the single Prisma client located at packages/shared/src/utils/database/prismaClient.ts; maintain schema in repo root at prisma/schema.prisma; run migrations from root using npm run db:migrate
Use Redis client and operations located in packages/shared/src/services/redis/; use for cache, sessions, and rate limits as defined by existing keys and types
Use typed errors from packages/shared/src/types/errors/ for domain failures; avoid using generic Error for application-specific failures
Use shared log and monitoring utils for logging and monitoring in production code paths; do not use direct console statements for production logging

Files:

  • packages/shared/src/utils/requiredDatabaseRelations.ts
  • packages/shared/src/utils/index.ts
packages/shared/**/*

📄 CodeRabbit inference engine (.cursor/rules/subagent-data.mdc)

Shared client and services must be located in packages/shared

Files:

  • packages/shared/src/utils/requiredDatabaseRelations.ts
  • packages/shared/src/utils/index.ts
**/{.scripts,scripts}/**/*.{sh,bash,js,ts}

📄 CodeRabbit inference engine (.cursor/rules/scripts-terminal.mdc)

Use cross-platform deletion utilities instead of OS-specific rm -rf

Files:

  • scripts/deploy.sh
{scripts/**,packages/scripts/**}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Prefer packages/scripts or root scripts/ for one-off automation; avoid maintaining one-time scripts in the repository long term

Files:

  • scripts/deploy.sh
{**/scripts/**,scripts/**,.github/workflows/**/*.{yml,yaml},**/.gitlab-ci.yml,.circleci/config.yml}

📄 CodeRabbit inference engine (.cursor/rules/workflow.mdc)

{**/scripts/**,scripts/**,.github/workflows/**/*.{yml,yaml},**/.gitlab-ci.yml,.circleci/config.yml}: Use cross-platform environment handling in scripts, cross-platform deletion utilities instead of OS-specific commands, pass non-interactive flags (--yes, --ci) by default in automation, and avoid OS-specific commands
Ensure logs are stream-friendly (no pagers) in scripts; when a pager might be used, pipe to cat

Files:

  • scripts/deploy.sh
**/index.ts

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

Use index.ts only to re-export a small, intentional surface per module

Files:

  • packages/shared/src/utils/index.ts
{CHANGELOG.md,README.md}

📄 CodeRabbit inference engine (.cursor/rules/agent-rules.mdc)

ALWAYS update CHANGELOG.md and README.md as changes are made.

Files:

  • CHANGELOG.md
CHANGELOG.md

📄 CodeRabbit inference engine (.cursor/rules/templates-examples.mdc)

CHANGELOG.md must be updated with all changes in pull requests

Always update CHANGELOG.md with all code changes

Update CHANGELOG.md with all changes, include breaking changes documentation, and reference issues and PRs

Files:

  • CHANGELOG.md
🧠 Learnings (19)
📓 Common learnings
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-09T20:22:47.453Z
Learning: For schema, migrations, and database/Redis operations in the shared package, use the `prisma-redis-lucky` skill
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-shared.mdc:0-0
Timestamp: 2026-03-09T20:21:15.595Z
Learning: Applies to packages/shared/**/*.ts : Use the single Prisma client located at `packages/shared/src/utils/database/prismaClient.ts`; maintain schema in repo root at `prisma/schema.prisma`; run migrations from root using `npm run db:migrate`
📚 Learning: 2026-03-09T20:21:15.595Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-shared.mdc:0-0
Timestamp: 2026-03-09T20:21:15.595Z
Learning: Applies to packages/shared/**/*.ts : Use the single Prisma client located at `packages/shared/src/utils/database/prismaClient.ts`; maintain schema in repo root at `prisma/schema.prisma`; run migrations from root using `npm run db:migrate`

Applied to files:

  • packages/backend/src/startup/verifyRequiredDatabaseState.ts
  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/shared/src/utils/requiredDatabaseRelations.ts
  • scripts/deploy.sh
  • packages/shared/src/utils/index.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
📚 Learning: 2026-03-09T20:22:47.453Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-09T20:22:47.453Z
Learning: For schema, migrations, and database/Redis operations in the shared package, use the `prisma-redis-lucky` skill

Applied to files:

  • packages/backend/src/startup/verifyRequiredDatabaseState.ts
  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • scripts/deploy.sh
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/**/*.{ts,tsx} : Use services from `lucky/shared` (DatabaseService, Redis client) for database and cache access; do not instantiate Prisma or Redis directly in the bot package

Applied to files:

  • packages/backend/src/startup/verifyRequiredDatabaseState.ts
  • packages/shared/src/utils/requiredDatabaseRelations.ts
  • packages/shared/src/utils/index.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
📚 Learning: 2026-03-09T20:21:38.098Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-backend.mdc:0-0
Timestamp: 2026-03-09T20:21:38.098Z
Learning: Applies to packages/backend/**/*.ts : Use `lucky/shared` for config and DB/Redis when needed in backend code

Applied to files:

  • packages/backend/src/startup/verifyRequiredDatabaseState.ts
📚 Learning: 2026-03-09T20:22:47.453Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-09T20:22:47.453Z
Learning: Use database commands: `npm run db:generate` for Prisma generation, `npm run db:migrate` for migrations, `npm run db:deploy` for deployment, `npm run db:studio` for database studio

Applied to files:

  • packages/backend/src/startup/verifyRequiredDatabaseState.ts
  • packages/shared/src/utils/requiredDatabaseRelations.ts
  • scripts/deploy.sh
📚 Learning: 2026-03-09T20:21:52.065Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-discord.mdc:0-0
Timestamp: 2026-03-09T20:21:52.065Z
Learning: Applies to packages/bot/src/**/*.ts : Use `lucky/shared` for database, Redis, logging, and embed utilities instead of implementing them locally

Applied to files:

  • packages/backend/src/startup/verifyRequiredDatabaseState.ts
  • packages/shared/src/utils/requiredDatabaseRelations.ts
  • packages/shared/src/utils/index.ts
📚 Learning: 2026-03-09T20:21:08.612Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-project.mdc:0-0
Timestamp: 2026-03-09T20:21:08.612Z
Learning: Applies to {packages/shared/**,prisma/**}/**/*.{ts,js} : Use Prisma for PostgreSQL database and Redis for caching with shared client configuration

Applied to files:

  • packages/backend/src/startup/verifyRequiredDatabaseState.ts
  • packages/shared/src/utils/requiredDatabaseRelations.ts
📚 Learning: 2026-03-09T20:21:46.291Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-data.mdc:0-0
Timestamp: 2026-03-09T20:21:46.291Z
Learning: Use `npm run db:deploy` command from repo root for deploying migrations

Applied to files:

  • docs/CI_CD.md
  • scripts/deploy.sh
📚 Learning: 2026-03-09T20:21:38.098Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-backend.mdc:0-0
Timestamp: 2026-03-09T20:21:38.098Z
Learning: Applies to packages/backend/tests/**/*.ts : Follow existing patterns for unit and integration tests in `packages/backend/tests/`

Applied to files:

  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
📚 Learning: 2026-03-09T20:20:38.694Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-backend-api.mdc:0-0
Timestamp: 2026-03-09T20:20:38.694Z
Learning: Applies to packages/backend/tests/**/*.{ts,tsx} : Organize tests in `packages/backend/tests/` with unit tests under `unit/` and integration tests under `integration/`, following existing patterns with fixtures and setup

Applied to files:

  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
📚 Learning: 2026-03-09T20:21:08.612Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-project.mdc:0-0
Timestamp: 2026-03-09T20:21:08.612Z
Learning: Applies to {packages/*/tests/**/*.test.{js,ts},tests/**/*.test.{js,ts}} : Add or adjust unit and integration tests when changing behavior; follow existing patterns in `packages/*/tests` and root `tests/` directories

Applied to files:

  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
📚 Learning: 2026-03-09T20:21:31.459Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/quality.mdc:0-0
Timestamp: 2026-03-09T20:21:31.459Z
Learning: Applies to tests/**/*.test.{ts,tsx,js,jsx} : Add integration tests where appropriate

Applied to files:

  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
📚 Learning: 2026-03-09T20:22:47.453Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-09T20:22:47.453Z
Learning: For unit tests and Jest ESM mocks, use the `testing-lucky` skill

Applied to files:

  • packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts
  • packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts
📚 Learning: 2026-03-09T20:21:46.291Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-data.mdc:0-0
Timestamp: 2026-03-09T20:21:46.291Z
Learning: Applies to prisma/migrations/**/* : Database migrations must be located in `prisma/migrations/`

Applied to files:

  • packages/shared/src/utils/requiredDatabaseRelations.ts
📚 Learning: 2026-03-09T20:21:46.291Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-data.mdc:0-0
Timestamp: 2026-03-09T20:21:46.291Z
Learning: Applies to prisma/schema.prisma : Schema definitions must be located in `prisma/schema.prisma`

Applied to files:

  • packages/shared/src/utils/requiredDatabaseRelations.ts
📚 Learning: 2026-03-09T20:21:46.291Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-data.mdc:0-0
Timestamp: 2026-03-09T20:21:46.291Z
Learning: Use `npm run db:generate` command from repo root for Prisma code generation

Applied to files:

  • scripts/deploy.sh
📚 Learning: 2026-03-09T20:21:15.595Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-shared.mdc:0-0
Timestamp: 2026-03-09T20:21:15.595Z
Learning: Applies to packages/shared/**/*.ts : Do not add dependencies on `bot` or `backend` packages; shared is the foundational package used by both

Applied to files:

  • packages/shared/src/utils/index.ts
📚 Learning: 2026-03-09T20:22:09.954Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/typescript.mdc:0-0
Timestamp: 2026-03-09T20:22:09.954Z
Learning: Applies to **/*.{ts,tsx,js,jsx} : Use named exports for clear usage and easier refactors

Applied to files:

  • packages/shared/src/utils/index.ts
🪛 GitHub Actions: CI/CD Pipeline
packages/shared/src/utils/requiredDatabaseRelations.ts

[error] 56-56: TS2352: Conversion of type 'PrismaClient' to type 'RequiredDatabaseStatePrisma' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

🪛 GitHub Actions: SonarCloud Analysis
packages/shared/src/utils/requiredDatabaseRelations.ts

[error] 56-56: Type conversion error: Conversion of type 'PrismaClient' to type 'RequiredDatabaseStatePrisma' may be a mistake. If intentional, convert the expression to 'unknown' first. [tsc] (TS2352) during build:shared step (tsc -b --force).

🔇 Additional comments (8)
packages/shared/src/utils/requiredDatabaseRelations.ts (1)

35-52: Good centralization of required-relation checks.

This relation-check table is clear and makes backend/deploy guard behavior consistent.

packages/shared/src/utils/index.ts (1)

9-9: Public re-export looks correct.

Exposing the shared relation guard here keeps consumption consistent from @lucky/shared/utils.

docs/CI_CD.md (1)

75-85: Deploy preflight docs are clear and aligned with behavior.

The added migration-status + relation-guard narrative is explicit and operationally useful.

packages/backend/src/startup/verifyRequiredDatabaseState.ts (1)

1-4: Nice simplification via shared guard delegation.

This keeps startup DB verification behavior centralized in one implementation.

CHANGELOG.md (1)

165-169: Changelog entry is accurate and scoped to the rollout guard changes.

scripts/deploy.sh (1)

253-280: Pre-rollout DB gate hardening is solid.

Running migrate status and the shared relation guard before restart is the right fail-fast sequence.

packages/backend/tests/unit/startup/requiredDatabaseRelations.test.ts (1)

38-130: Great coverage for the shared relation verifier contract.

Healthy path, per-table missing relation mapping, and unknown-error passthrough are all covered.

packages/backend/tests/unit/startup/verifyRequiredDatabaseState.test.ts (1)

21-47: Delegation-focused tests look correct.

These assertions capture the new contract: one shared guard call and unchanged error propagation.

Comment thread packages/shared/src/utils/requiredDatabaseRelations.ts
@sonarqubecloud

Copy link
Copy Markdown

@LucasSantana-Dev
LucasSantana-Dev dismissed coderabbitai[bot]’s stale review March 13, 2026 14:57

Addressed in commit 238ca88: removed unsafe cast, switched to generated Prisma Pick typing, and revalidated with type-check + tests.

@sonarqubecloud

Copy link
Copy Markdown

@LucasSantana-Dev
LucasSantana-Dev merged commit 64ab537 into main Mar 13, 2026
15 checks passed
@LucasSantana-Dev
LucasSantana-Dev deleted the fix/deploy-db-drift-guardrails branch March 13, 2026 15:07
LucasSantana-Dev added a commit that referenced this pull request May 13, 2026
* fix(deploy): fail fast on db drift before rollout

* fix(shared): satisfy prisma guard typing in ci build

* fix(shared): remove unsafe prisma cast in db guard

This branch was successfully deployed

1 active deployment
Preview — 238ca889 Deployed Mar 13, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant