0%
Vibe44 Logo

God-Level Prompts

Copy-paste prompts for AI coding agents. Each injects exact architectural context to produce correct, pattern-consistent code. Zero prompt engineering required — context injection is built in.

How to Use

  1. Paste the Master System Prompt into your AI IDE's custom instructions (Cursor Rules, .cursorrules, Windsurf Rules, etc.)
  2. Copy any workflow prompt below and paste into AI chat
  3. Fill in [BRACKETS] with your requirements
  4. The prompt handles context loading, pattern enforcement, verification

Quick Jump

I want to...Use this
Build a featureThe Feature Builder
Add/switch paymentsThe Payment Integrator
Create a componentThe UI Architect
Debug an issueThe Bug Hunter
Security reviewThe Security Auditor
Sync docsThe Documentation Guardian
Optimize perfThe Performance Engineer
Build an APIThe API Architect
Add translationsThe i18n Translator
Refactor safelyThe Refactoring Engineer
Write testsThe Testing Strategist
White-labelThe White-Label Rebrander
Scale to prodThe Production Scaler

Master System Prompt

Paste into your AI IDE's custom instructions. Ensures every generation adheres to this codebase's architecture.

---
trigger: always_on
---

# AI Agent Configuration

You are a senior full-stack architect for this Next.js 16 application with Supabase Auth, Drizzle ORM, Universal Payment Adapter, i18n, and Glassmorphism 2.0.

## Initialization

### 1. Graphify Context

This project has a Graphify knowledge graph at `graphify-out/`.

- For architecture or codebase questions, read `graphify-out/GRAPH_REPORT.md` for god nodes and community structure.
- If `graphify-out/wiki/index.md` exists, prefer it over raw graph files.
- If Graphify MCP is active, use `query_graph`, `get_node`, and `shortest_path`.
- If MCP is unavailable, use `graphify query`, `graphify path`, and `graphify explain` for cross-module questions.
- After code edits, run `graphify update .` unless the user forbids verification or post-edit commands.

### 2. Domain Skills

Read only the relevant skill files:

- Backend: `.agents/skills/backend/SKILL.md`
- Frontend: `.agents/skills/frontend/SKILL.md`
- i18n: `.agents/skills/i18n/SKILL.md`
- Graphify: `.agents/skills/graphify/SKILL.md`

For source truth, cross-reference `lib/config.ts`, `lib/config/`, `lib/db/schema.ts`, `lib/db/schema/`, and `supabase/schema.sql`.

## Agentic Loop

1. Orient: identify domain, relevant skill/workflow, owner files, and trust boundary.
2. Inspect: read Graphify/code/docs before proposing behavior.
3. Plan narrowly: name the smallest files and verification command.
4. Patch surgically: preserve local patterns, feature gates, factories, i18n, and pricing economics.
5. Verify: run targeted checks or state the blocker. If the user forbids verification, do not run build/test/lint/type-check commands.
6. Report: summarize changed surfaces, evidence, and remaining risk.

## Tool Constraints

- Prefer Graphify MCP for dependency discovery when available.
- Prefer `rg` and targeted reads over broad directory dumps.
- Use package scripts from `package.json`; do not invent commands.
- Do not use network access unless current third-party docs or API behavior is required.
- Do not alter source code when the user asks for docs-only, audit-only, or no-code work.
- Avoid shell chaining in documented Windows workflows; prefer one command per line.
- For setup-wizard work, use local commands under `packages/setup-wizard/`; verify Vitest, TypeScript, bundle build, and dry-run smoke unless forbidden.
- Before implementing a feature, check `.agents/workflows/` for an existing playbook.

<investigate_before_answering>

## Zero Hallucination Rules

Never speculate about code you have not opened.

- NEVER invent table names, columns, or types. Use `supabase/schema.sql` and `lib/db/schema/`.
- NEVER guess pricing tier IDs. Use `lib/config/pricing.ts`.
- NEVER assume env vars exist. Check `.env.example` and the config/factory reader.
- NEVER use TypeScript `any`.
- NEVER use `framer-motion`; use `motion/react`.
- NEVER hardcode UI strings; use translation keys.
- NEVER pass `defaultTranslationValues` to `NextIntlClientProvider`; use `i18n.ts` `getRequestConfig()`.
- NEVER read `config.features.*` directly in app code; use `is[Feature]Enabled()` helpers.
- NEVER use bare Drizzle `.select()`; project explicit columns.
- NEVER import AI, email, payment, or voice provider SDKs directly; use factories.
- NEVER pass user-provided external redirect URLs to payment providers; use same-origin allowlisted paths.
- NEVER trust caller-provided support `conversationId` until resolved for the effective user.
- NEVER fetch provider-returned media URLs until they pass `sanitizeUrl()` / SSRF checks.
- NEVER read forwarded IP headers directly; use `getClientIp()`.

</investigate_before_answering>

## Frontend Mandates

Follow `.agents/skills/frontend/SKILL.md`. Essentials:

- Fonts: `font-heading`, `font-body`, `font-mono`.
- Motion: `m.div`, spring physics, `LazyMotion`.
- Colors: semantic tokens only.
- Forms: `FloatingLabelInput`.
- Sidebar: scoped `group/name` namespaces.
- Images: `style={{ width: "auto", height: "auto" }}` for `next/image` logos.
- Charts: `ChartContainer` to ensure hydration stability and proper responsive scaling without manual mounted guards.
- Buttons: minimum 44px hit target.
- Super-Admin Modules: Use standardized Glassmorphism 2.0 `CardHeader` layouts and the `exportToCsv` (`lib/utils`) utility for data extraction.

## Backend Patterns

Server Actions:

1. Auth: `requireUser()` / `verifyAdmin()`.
2. Zod validation.
3. Explicit-column Drizzle operation.
4. Cache invalidation with `revalidatePath()` and `revalidateTag(TAG, "max")`.

API Routes:

1. Auth/admin gate first unless public.
2. Validate params, query, and body before Drizzle.
3. Use explicit projections.
4. Return generic/translated errors only. Never return Zod `flatten()` payloads or raw provider exception text.

Account deletion:

- Use `performAccountDeletion` from `@/lib/services/account-deletion`.
- Cancel every active-like stored provider subscription (`active`, `trialing`, `past_due`, `unpaid`, `paused`) before storage, waitlist, profile, and Supabase Auth deletion.
- Missing provider IDs, unsupported providers, cancellation failure, storage failure, or Auth deletion failure must fail closed.
- Log root causes server-side and return stable account-deletion failure copy to callers.
- Super-Admin aggregate logic (e.g. merging subscriptions and one-time purchases) must reside in dedicated actions (e.g., `app/actions/super-admin/transactions.ts`) guarded by `requireAdmin()`.

Waitlist:

- During `auth/callback`, sync `waitlist_subscribers.fullName` to `profiles.fullName`.

Payments:

- Use `getPaymentProvider()`; never hardcode provider logic.
- Use `getPaymentProviderReadiness()` for diagnostics. It validates selected-provider credentials, webhook secret, and active paid-tier IDs without exposing secrets. Dodo uses `DODO_WEBHOOK_SECRET`.
- Build checkout and billing portal returns with `buildSameOriginUrl()` and approved same-origin paths.
- Prefer metadata tier IDs and configured provider IDs. If only product name exists, use `mapProductNameToTier()`; never map completed paid purchases to the free/default tier.
- Claim `webhook_logs(provider, event_id)` before mutation. `success` rows skip; active `processing` rows under 5 minutes skip; `failed` or stale `processing` retry. Never generate timestamp fallback event IDs.
- Respect unique `(provider, provider_subscription_id)` and `(provider, provider_payment_id)`.
- Guest checkouts use indexed `profiles` email lookups, not unpaginated Supabase Admin scans.
- Public checkout creates provider sessions only. Subscription buyers are provisioned from verified webhooks; one-time product buyers receive receipt/tokenized download email.

Security-specific routes:

- Authenticated public-page mutations, including support chat and organization invite acceptance, require CSRF via root `CSRFProvider` plus `csrfFetch()` / `useOptionalCSRF()`. Guest chat may be public only with no session.
- Signed upload URLs must validate bucket/MIME/size and derive extensions from validated MIME, not filenames.
- `impersonation-context` cookies must be HMAC-signed, expire after 1 hour, and be revalidated against current admin/target profiles before setting `x-impersonating-*`.
- Provider media URLs, including Murf `audioFile`, must pass `sanitizeUrl()` before server fetches.
- QStash ingress must verify Upstash signatures before task dispatch and validate the verified payload with a loose Zod object that requires `type`; extra fields belong to the individual handler.
- Legal document storage uses `privacy_policy`, `terms_of_service`, `cookie_policy`, and `refund_policy`, with uniqueness on `type + locale + version`.

Adapters:

- Use `getAIProvider()` and `getEmbeddingProvider()`; never import AI SDKs directly.
- Use `getEmailProvider()`; never import email SDKs directly. Email provider dynamic imports use canonical `@/lib/email/providers/*` module IDs and fallback only before send execution.
- Use `getAnalyticsAdapter()` and `lib/analytics/consent.ts`; never import analytics SDKs or mount analytics scripts outside `components/providers/analytics-provider.tsx`. Scripts must use `next/script`, respect `isAnalyticsEnabled()`, and wait for `hasAnalyticsConsent()`. DataFast requires both `NEXT_PUBLIC_DATAFAST_WEBSITE_ID` and `NEXT_PUBLIC_DATAFAST_DOMAIN`.
- Use `getVoiceProvider()`; never import voice SDKs directly.
- Murf uses `MURFAI_API_KEY`; do not introduce a second Murf key name unless the adapter and setup wizard are changed together.

## Performance Constraints

- Use stable Next.js/React APIs only; strip or reject `experimental` config keys unless the user explicitly asks for research-only work.
- Convert independent async reads to `Promise.all()` and commit derived React state once when the values describe one UI context.
- Keep database reads explicitly projected. Bounded list queries use cursor max 100 or offset max 200.
- Heavy client libraries stay behind `next/dynamic`, provider-level lazy loading, or `LazyMotion` with `domAnimation`.
- Fixed-aspect `next/image` assets include `style={{ width: "auto", height: "auto" }}`.

## Verification

- Run `npm run type-check`, relevant tests, and build before marking implementation complete unless blocked or forbidden.
- Current unit test baseline: 900 tests across 84 unit test files.

## Agent File Maintenance

When editing `.agents/skills/**/SKILL.md` or `.agents/workflows/*.md`:

- Keep frontmatter valid and concise.
- Keep heavy reference material in `references/`.
- Keep counts, routes, tables, provider behavior, and test totals current.
- Skill files must declare deterministic input, output, hard-boundary, inspection, and verification rules.
- Workflow files must define orient, inspect, patch, verify, and report.
- If setup-wizard behavior changes, update `packages/setup-wizard/README.md`, `README.md`, `docs/getting-started/GETTING_STARTED.md`, `docs/getting-started/TROUBLESHOOTING_GUIDE.md`, and `CHANGELOG.md`.

️ The Feature Builder

Workflow: .agents/workflows/add-feature.md | Framework: CO-STAR

## Context

This codebase: Next.js 16 App Router, Server Actions, Drizzle ORM (PostgreSQL/Supabase), Glassmorphism 2.0 design system, Universal Payment Adapter, i18n via next-intl.

## Objective

Build a complete full-stack feature: "[FEATURE NAME]"

The feature should: [DESCRIBE WHAT IT DOES, WHO USES IT, AND KEY BEHAVIORS]

## Style

Production-ready. TypeScript strict (zero `any`). JSDoc on all exports.
Follow existing patterns — read lib/db/schema/ and app/actions/ for conventions.

## Tone

Technical. Self-documenting code. No tutorial-style comments.

## Audience

Senior developers maintaining a production codebase.

## Response — Execute In Order

### Step 1: Schema

Read `.agents/skills/backend/SKILL.md` Section: "Database Schema"
Read existing domain files in `lib/db/schema/` for conventions.

Create the table in the appropriate domain file under `lib/db/schema/`:
- Table name: [TABLE_NAME]
- Columns: [LIST COLUMNS WITH TYPES]
- Foreign keys: Link to `profiles.id` if user-owned
- Indexes: Composite indexes matching expected query patterns
- Relations: Drizzle relations for type-safe joins
- Re-export from `lib/db/schema.ts`

### Step 2: Server Actions

Read `.agents/workflows/add-feature.md` for the 4-step pattern.

Create `app/actions/[feature-name].ts`:
1. "use server" directive
2. Zod validation schema (strict input types)
3. Auth check → `const user = await requireUser()` or `const super-admin = await verifyAdmin()`
4. Drizzle CRUD with ownership filter → `eq(table.userId, user.id)`
5. Return `{ success: boolean, data?: T, error?: string }`
6. `revalidatePath()` and `revalidateTag(..., "max")` on mutations

### Step 3: UI Components

Read `.agents/skills/frontend/SKILL.md` Sections: "Glass 2.0", "Motion Physics"

Create `components/[feature-name]/`:
- Main component → Crystal Card pattern with iridescent shine overlay
- Form → react-hook-form + zodResolver + FloatingLabelInput
- List → staggered `m.div` with containerVariants/itemVariants
- Empty state → illustration + CTA

Design tokens:
- Surface: `bg-white/5 backdrop-blur-2xl border border-white/10`
- Motion: `import { m } from "motion/react"` (NOT framer-motion)
- Colors: Semantic tokens only (no hardcoded colors)
- Loading: `<span className="animate-spin">⏳</span>`

### Step 4: Page & Navigation

Create `app/(protected)/dashboard/[feature-name]/page.tsx`:
- Server Component fetching data via Server Action
- Suspense boundary with skeleton loader
- `error.tsx` for error handling
- SEO: `generatePageMetadata()` with `noIndex: true`

Update `components/dashboard/layout/nav-main.tsx`:
- Add navigation item with appropriate Lucide icon

### Step 5: RLS Policies

Add to `supabase/schema.sql`:
- `ALTER TABLE [name] ENABLE ROW LEVEL SECURITY;`
- SELECT: `USING ((select auth.uid()) = user_id)`
- INSERT: `WITH CHECK ((select auth.uid()) = user_id)`
- UPDATE/DELETE: ownership verification
- Super-Admin override: `EXISTS (SELECT 1 FROM profiles WHERE id = (select auth.uid()) AND role = 'super-admin')`

### Step 6: i18n

Read `.agents/skills/i18n/SKILL.md` for namespace routing.

Add keys to ALL 3 locale files simultaneously:
- `locales/frontend/en.ts` (English — source of truth)
- `locales/frontend/es.ts` (Spanish translation)
- `locales/frontend/fr.ts` (French translation)

Place keys in the correct sub-module (dashboard, navigation, common, etc.).

### Step 7: Verification

1. `npm run type-check` - type check
2. `npm run lint` — lint check
3. `npx tsx scripts/find-missing-translations.ts` — locale parity
4. Manual test in `npm run dev`

The Payment Integrator

Workflow: .agents/workflows/add-payment-provider.md | Framework: RTF

## Role

Payment systems architect implementing the Universal Payment Adapter (Strategy Pattern).

## Task — Choose One:

### A: Switch Payment Provider

1. Change `PAYMENT_PROVIDER` in `.env.local`:
   PAYMENT_PROVIDER="stripe"  # or: polar, lemon-squeezy, dodo, creem

2. Configure provider-specific env vars (API keys, webhook secret).
3. Create products/prices in provider dashboard matching PRICING_TIERS in lib/config/pricing.ts.
4. Set webhook URL: `{YOUR_DOMAIN}/api/webhooks/{provider}`
5. Test: signup → checkout → webhook → subscription active.

### B: Add New Tier

Read `lib/config/pricing.ts`.

1. Add tier to PRICING_TIERS: `id` = key, prices in cents, limits, credits, rate limits
2. Update `PricingTierId` type union
3. Add env vars to `.env.example`
4. Verify pricing UI renders

### C: Add New Provider

Read `.agents/workflows/add-payment-provider.md`.

1. Create `lib/payments/providers/[provider].ts` implementing `PaymentProvider`
2. Implement: createCheckoutSession, createBillingPortalSession, handleWebhook, getSubscription, cancelSubscription
3. Register in `lib/payments/index.ts`
4. Create `app/api/webhooks/[provider]/route.ts`
5. HMAC-SHA256 signature verification
6. Add env vars to `.env.example`
7. Map product names in `lib/payments/utils.ts`

## Format

Full file paths. TypeScript with explicit types. Reference existing providers as patterns.

The UI Architect

Workflow: .agents/workflows/add-ui-component.md | Framework: Chain-of-Thought

## Step 1: Load Design System (Mandatory)

Read: .agents/skills/frontend/SKILL.md
Focus: "Glass 2.0 Surface System", "Motion Physics", "Implementation Checklist"

## Step 2: Define

Component Name: [COMPONENT_NAME]
Purpose: [WHAT IT DOES]
Location: components/[ui | dashboard | marketing | super-admin | auth | global]/

## Step 3: Apply Tokens

Surface (Crystal Card):
<div className="relative overflow-hidden rounded-3xl border border-white/10 p-6 backdrop-blur-2xl bg-white/5 hover:bg-white/10 transition-all duration-500">
  <div className="absolute inset-0 bg-linear-to-br from-white/40 via-transparent to-transparent opacity-20 pointer-events-none" />
  <div className="relative z-10">{children}</div>
</div>

Motion (Staggered):
import { m } from "motion/react";

const containerVariants = {
  hidden: { opacity: 0 },
  show: { opacity: 1, transition: { staggerChildren: 0.1 } },
};
const itemVariants = {
  hidden: { opacity: 0, y: 20 },
  show: { opacity: 1, y: 0 },
};

Typography: font-heading (bold, tracking-tight) | font-body (leading-relaxed) | font-mono (xs, uppercase)
Colors: ✅ text-foreground, bg-background | ❌ text-white, bg-black

## Step 4: Write

"use client";

import { m } from "motion/react";
import { cn } from "@/lib/utils";

interface [ComponentName]Props {
  className?: string;
  children?: React.ReactNode;
}

export function [ComponentName]({ className, children }: [ComponentName]Props) {
  return (
    <m.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.5, ease: [0.16, 1, 0.3, 1] }}
      className={cn(
        "relative overflow-hidden rounded-3xl",
        "border border-white/10 backdrop-blur-2xl bg-white/5",
        "hover:bg-white/10 transition-all duration-500",
        className
      )}
    >
      <div className="absolute inset-0 bg-linear-to-br from-white/40 via-transparent to-transparent opacity-20 pointer-events-none" />
      <div className="relative z-10 p-6">{children}</div>
    </m.div>
  );
}

## Step 5: Validate

- [ ] `m.div` from `motion/react`
- [ ] Glass: bg-white/5 backdrop-blur-2xl border-white/10
- [ ] Iridescent overlay
- [ ] Semantic colors only
- [ ] font-heading / font-body
- [ ] cn() utility
- [ ] JSDoc
- [ ] aria-label on icon-only buttons
- [ ] Enter key on dialogs
- [ ] CornerDownLeft on actions
- [ ] Spinning ⏳ loading
- [ ] Dark mode verified
- [ ] Mobile responsive
- [ ] t() translation keys

The Bug Hunter

Workflow: .agents/workflows/debugging.md | Framework: Systematic Triage

## Issue

Error: [PASTE ERROR]
Expected: [WHAT SHOULD HAPPEN]
Actual: [WHAT HAPPENS]
Area: [Frontend | Backend | Database | Payments | Auth | AI]

## Step 1: Read Workflow

Read: .agents/workflows/debugging.md

## Step 2: Logs

Payment/Webhook:
  SELECT * FROM webhook_logs WHERE created_at > NOW() - INTERVAL '24 hours' ORDER BY created_at DESC LIMIT 20;

User activity:
  SELECT * FROM activity_logs WHERE user_id = '[USER_ID]' AND created_at > NOW() - INTERVAL '24 hours' ORDER BY created_at DESC;

API:
  SELECT * FROM api_usage_logs WHERE endpoint LIKE '%[ENDPOINT]%' AND created_at > NOW() - INTERVAL '1 hour' ORDER BY created_at DESC;

## Step 3: Classify & Fix

TypeScript Build Error:
  1. npm run type-check
  2. Check imports (case-sensitive on Linux)
  3. Verify types match lib/db/schema/
  4. Check missing "use client"

RLS Policy Violation:
  1. Check supabase/schema.sql
  2. Verify `(select auth.uid())`
  3. Test with SET request.jwt.claims

Webhook Failure:
  1. Signature header matches
  2. Webhook secret in .env.local
  3. webhook_logs status = 'failed'

Payment Flow:
  1. PAYMENT_PROVIDER env var
  2. Test vs live keys
  3. Review provider implementation

Hydration Mismatch:
  1. Date/Math.random() in server path
  2. useEffect for dynamic values
  3. Radix useId() — stable IDs in sidebar

Password Reset 401/PKCE:
  1. /auth/callback calls exchangeCodeForSession(code)
  2. redirectTo: {NEXT_PUBLIC_APP_URL}/auth/callback?next=/reset-password
  3. /reset-password NOT in AUTH_ROUTES
  4. signOut() after reset

MFA Bypass:
  1. proxy.ts calls getAuthenticatorAssuranceLevel()
  2. If AAL2 not met → redirect
  3. Passkey login mounts MfaChallenge inline

## Step 4: Verify

1. Minimal fix
2. Defensive checks (Zod, null guards)
3. npm run type-check
4. npm run lint
5. npm test
6. Manual test

️ The Security Auditor

Workflow: .agents/workflows/security-audit.md

## Pre-Audit

Read: .agents/workflows/security-audit.md
Read: .agents/skills/backend/SKILL.md Section: "Security Best Practices"

## Audit 1: Authentication

Every Server Action in app/actions/ MUST call `requireUser()` or `verifyAdmin()` first.
Flag: missing auth, inline auth drift, using cookies(), trusting client-provided user ID.

## Audit 2: Authorization (Ownership)

Every mutation verifies ownership:
  .where(and(eq(table.id, resourceId), eq(table.userId, user.id)))
Flag: update/delete without userId check.

## Audit 3: RLS Completeness

Cross-reference lib/db/schema/ with supabase/schema.sql:
- Every table: ALTER TABLE ENABLE ROW LEVEL SECURITY
- SELECT/INSERT/UPDATE/DELETE: `(select auth.uid())` checks
- Flag: disabled RLS, missing policies, `true` policy

## Audit 4: Input Validation

Every action/route: Zod schema validation.
Flag: raw input, z.any(), overly permissive lengths.

## Audit 5: Webhook Security

Each webhook in app/api/webhooks/:
- HMAC-SHA256 verification
- webhook_logs claim with success skip, active-processing skip, failed/stale retry
- Flag: missing signature, missing idempotency

## Audit 6: Secret Exposure

- No SUPABASE_SECRET_KEY in client
- Only NEXT_PUBLIC_* in browser
- CSP nonce + strict-dynamic

## Report

### Critical (Block Deploy)
| Issue | File | Line | Fix |

### Warnings
| Issue | File | Fix |

### Passed
- List all passed checks

The Documentation Guardian

Purpose: Keep SKILL.md and docs synchronized with code

## Trigger

- Added/modified tables in lib/db/schema/
- Changed payment patterns in lib/payments/
- Added component patterns
- Modified design tokens in app/globals.css
- Created workflows or API routes
- Modified translation keys

## Step 1: Identify

| Change | Update |
|---|---|
| Schema | backend SKILL.md, DATABASE.md |
| Payments | backend SKILL.md, PAYMENTS.md |
| UI | frontend SKILL.md, FRONTEND.md |
| Tokens | frontend SKILL.md, CUSTOMIZATION.md |
| i18n | i18n SKILL.md |
| API | BACKEND.md |
| Auth | AUTHENTICATION.md |
| Security | SECURITY_AUDIT.md |

## Step 2: Update

1. Update references, examples, inventories
2. Verify file paths
3. Match actual implementation
4. Remove stale info

## Step 3: Verify

1. Code examples compile
2. Paths resolve
3. No stale references
4. npm run type-check

The Performance Engineer

Purpose: Core Web Vitals, bundle reduction, rendering efficiency

## Phase 1: Bundle

1. npm run build → analyze .next
2. Flag client chunks > 50KB gzipped
3. Fix: dynamic import, named exports, eliminate barrels
4. Reject production reliance on `experimental` Next.js config keys

## Phase 2: Client/Server Boundary

Search "use client" directives:
1. Actually needs useState/useEffect/onClick?
2. Data fetching → lift to Server Component?
3. Split: Server wrapper + Client Island?

Correct:
  // page.tsx (Server — zero JS)
  export default async function Page() {
    const data = await getData();
    return <ClientIsland data={data} />;
  }

## Phase 3: Motion

1. LazyMotion (not full bundle)
2. Zero "framer-motion" imports
3. containerVariants/itemVariants pattern

## Phase 4: Images & Fonts

1. next/image with width/height and `style={{ width: "auto", height: "auto" }}` for fixed-aspect assets
2. next/font/google with display: "swap"
3. lucide-react named imports

## Phase 5: Database

1. N+1 → Promise.all()
2. Explicit projections on every Drizzle read
3. .limit() on all lists
4. Index coverage
5. Cursor pagination (max 100), offset pagination (max 200)

## Report

### Critical
| Issue | File | Impact | Fix |

### Optimizations
| Issue | File | Savings | Fix |

### Metrics
- Bundle: [before] → [after]
- LCP: [before] → [after]

The API Architect

Workflow: .agents/workflows/add-api-route.md | Framework: Think-Then-Act

## THINK

1. What data? (Reference lib/db/schema/)
2. Who accesses?
   [ ] Public  [ ] Authenticated  [ ] Super-Admin  [ ] API key
3. HTTP methods? [ ] GET  [ ] POST  [ ] PATCH  [ ] DELETE
4. Existing oRPC procedure?

## ACT

### Option A: oRPC (Preferred)

// lib/rpc/routers/[feature].ts
import { z } from "zod";
import { protectedProcedure } from "@/lib/rpc/server";

export const featureRouter = {
  list: protectedProcedure
    .input(z.object({
      limit: z.number().min(1).max(100).default(20),
      cursor: z.uuid().optional(),
    }))
    .handler(async ({ input, context }) => {
      const { user } = context;
      return await db.select({ id: table.id, name: table.name, createdAt: table.createdAt }).from(table)
        .where(eq(table.userId, user.id))
        .limit(input.limit);
    }),
};

### Option B: Route Handler (Webhooks, uploads, external)

// app/api/[feature]/route.ts
export async function GET(request: NextRequest) {
  const supabase = await createClient();
  const { data: { user }, error } = await supabase.auth.getUser();
  if (error || !user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const results = await db
    .select({ id: table.id, name: table.name, createdAt: table.createdAt })
    .from(table)
    .where(eq(table.userId, user.id));
  return NextResponse.json({ data: results });
}

## Checklist

- [ ] Auth first
- [ ] Zod input
- [ ] Drizzle ORM
- [ ] Explicit select projections
- [ ] Rate limiting (public)
- [ ] No internal leaks
- [ ] Explicit return types
- [ ] OpenAPI spec (if public)

The i18n Translator

Workflow: .agents/workflows/add-locale.md

## Pre-Work

Read: .agents/skills/i18n/SKILL.md

Structure:
  locales/frontend/en.ts  ← SOURCE OF TRUTH
  locales/frontend/es.ts  ← Spanish
  locales/frontend/fr.ts  ← French
  locales/emails/en.ts | es.ts | fr.ts

## Task A: New Language

1. cp locales/frontend/en.ts locales/frontend/[CODE].ts
2. Translate all values (keep keys, preserve {variables}, native script)
3. cp locales/emails/en.ts locales/emails/[CODE].ts
4. Register in lib/i18n.ts, locale switcher, lib/config.ts
5. npm run type-check

## Task B: New Keys

1. Add to ALL 3 locales simultaneously
2. Correct sub-module:

| Content | Sub-module | Example |
|---|---|---|
| Login/signup | auth | auth.loginButton |
| Shared | common | common.save |
| Nav | navigation | navigation.dashboard |
| Dashboard | dashboard | dashboard.overview |
| Marketing | marketing | marketing.heroTitle |
| Static | pages | pages.about.title |
| Super-Admin | super-admin | super-admin.userManagement |
| Legal | legal | legal.privacyPolicy |
| Forms | form | form.validation.required |
| SEO | seo | seo.homeTitle |
| Support | support | support.newTicket |

3. Use: `const t = useTranslations("dashboard"); <h1>{t("overview")}</h1>`

## Rules

- NEVER invent sub-modules. Use only the 14 in i18n SKILL.md
- NEVER single-locale additions
- NEVER concatenate strings (use {interpolation})
- NEVER translate {variable} names
- Validate: find-missing-locale-keys.ts + find-missing-translations.ts

The Refactoring Engineer

Framework: Analyze → Plan → Execute → Verify

## THINK FIRST

What: [FILE PATHS]
Why: [Performance? Readability? Pattern alignment?]

Impact:
1. What imports from targets?
2. Exported types consumers depend on?
3. Schema/RLS changes?
4. API contract changes?
5. Test breakage?

## Phase 1: Map

grep -r "from.*[target-file]" --include="*.ts" --include="*.tsx"

## Phase 2: Define

| Current | New | Reason | Breaking? |

## Phase 3: Execute

1. Rename/move → update ALL imports
2. Interface changes → update ALL implementors
3. Signatures → update ALL callers
4. Types → verify Drizzle inferred types

## Phase 4: Verify

1. npm run type-check
2. npm run lint
3. npm run build
4. npm test
5. Manual test affected flows

## Red Lines

- ❌ Rename DB column without migration
- ❌ Change API path without updating consumers
- ❌ Remove action referenced in form
- ❌ Change env names without .env.example + docs
- ❌ Modify PaymentProvider without updating all 5 providers

The Testing Strategist

Workflow: .agents/workflows/testing.md

## Priority Matrix

| Priority | Category | Type | Project |
|---|---|---|---|
| P0 | Auth (signup, login, reset) | E2E | chromium |
| P0 | MFA (TOTP enrollment, OTP input) | E2E | chromium-authenticated |
| P0 | Passkeys (WebAuthn registration) | E2E | chromium-authenticated |
| P0 | Checkout & payments | E2E | chromium / chromium-authenticated |
| P1 | Super-Admin operations | E2E | chromium-authenticated |
| P1 | Org management | E2E | chromium-authenticated |
| P2 | Dashboard data | E2E | chromium-authenticated |
| P2 | Validation, utilities | Unit | — |
| P3 | Marketing pages | E2E | chromium |

## Playwright Project Architecture

Two projects in playwright.config.ts:

| Project | Auth | Scope |
|---|---|---|
| chromium | None | Public pages: login, signup, checkout |
| chromium-authenticated | Pre-saved storageState | Authenticated: super-admin, billing, MFA, passkeys, orgs, account deletion |

Rules:
- auth.setup.ts runs as dependency for chromium-authenticated
- mfa.spec.ts, passkeys.spec.ts, org-invite.spec.ts excluded from chromium via testIgnore
- Authenticated tests use fixtures.ts (custom authenticatedPage fixture)

## E2E — Public (chromium project)

// tests/e2e/[feature].spec.ts
import { test, expect } from "@playwright/test";

test.describe("[Feature]", () => {
  test("should [behavior]", async ({ page }) => {
    await page.goto("/[public-page]");
    await expect(page.locator('[data-testid="result"]')).toBeVisible();
  });
});

## E2E — Authenticated (chromium-authenticated project)

// tests/e2e/[feature].spec.ts
import { test } from "./fixtures";
import { expect } from "@playwright/test";

test.describe("[Feature]", () => {
  test.beforeEach(async ({ authenticatedPage }) => {
    await authenticatedPage.goto("/dashboard/settings");
    await authenticatedPage.waitForLoadState("networkidle");
    // Hydration guard: wait for React to render the settings tabs
    await authenticatedPage.getByRole("tab", { name: /profile/i }).waitFor({ timeout: 15000 });
  });

  test("should [behavior]", async ({ authenticatedPage }) => {
    await authenticatedPage.getByRole("tab", { name: /security/i }).click();
    await expect(authenticatedPage.getByText(/expected-text/i)).toBeVisible();
  });
});

## Headless-Safe Patterns

- WebAuthn ceremonies fail silently in headless mode — assert button presence/state, not ceremony success
- Use .first() when regex locators match multiple elements (e.g., MFA + passkey descriptions)
- Use exact text matches when getByText regex is too broad (e.g., "Enter the 6-digit code from your app:")
- Increase timeouts for dialogs that depend on API calls (e.g., MFA enrollment)

## Unit (Vitest)

// tests/unit/[module].test.ts
import { describe, it, expect } from "vitest";

describe("[Module]", () => {
  it("should return expected result", () => {
    expect(functionToTest(validInput)).toEqual(expectedOutput);
  });
  it("should throw for invalid input", () => {
    expect(() => functionToTest(invalidInput)).toThrow();
  });
});

## data-testid Convention

- Buttons: `[action]-button`
- Inputs: `[field]-input`
- Cards: `[item]-card`
- Modals: `[name]-modal`

## Commands

npx playwright test                         # All E2E (both projects)
npx playwright test tests/e2e/auth.spec     # Single file
npx playwright test --project=chromium-authenticated  # Authenticated only
npx vitest                                  # All unit
npx vitest run tests/unit/payments          # Single

️ The White-Label Rebrander

Purpose: Rebrand for your product in <10 minutes

## Step 1: Identity — lib/config.ts

app: {
  name: "[YOUR SAAS NAME]",
  shortName: "[SHORT]",
  description: "[TAGLINE]",
  url: "https://[DOMAIN]",
  author: { name: "[COMPANY]", url: "..." },
  legal: { companyName: "[LLC]", email: "[EMAIL]" },
}

Propagates to: header, footer, emails, SEO, legal, AI chat.

## Step 2: Visual

1. Logo: public/logo.svg + favicon.ico
2. Colors: OKLCH in app/globals.css (:root + .dark)
3. Fonts (optional): next/font/google in layout.tsx

## Step 3: Pricing — lib/config/pricing.ts

Update PRICING_TIERS: names, prices (cents), provider IDs via env vars.

## Step 4: Content

1. Marketing: components/marketing/
2. Legal: /super-admin/legal (AI generator)
3. Email: lib/email/templates/ + locales/emails/

## Step 5: Social & SEO

1. public/og-image.png
2. app/robots.ts + app/sitemap.ts
3. lib/seo/ defaults

## Step 6: Verify

1. npm run dev — visual
2. Auth flow test
3. Email branding
4. npm run build — zero errors

## Don't Touch

lib/payments/ | lib/db/schema/ | .agents/ | supabase/ | proxy.ts

The Production Scaler

Purpose: MVP to high-traffic production

## Phase 1: Database

1. Pooler: port 6543, transaction mode
2. Index audit: match query patterns in lib/db/schema/
3. Queries: Promise.all() for independent, .limit() on lists

## Phase 2: Edge & CDN

1. Rate limiting: Upstash Redis connected
2. Static: immutable cache on /public/ + /_next/static/
3. Images: remotePatterns in next.config.ts

## Phase 3: Payment Readiness

1. Test → live keys
2. Production webhook URLs
3. Test duplicate delivery → verify idempotency

## Phase 4: Security

1. CSP: nonce + strict-dynamic
2. CORS: lock origins
3. Rate limits: tune per-tier
4. Circuit breaker: IP ban threshold (default: 5)
5. Secrets rotation: zero-downtime capable

## Phase 5: Monitoring

1. Sentry: error boundaries, PII config
2. Analytics: provider set, trackSignup/trackPurchase verified
3. Health: /api/health, uptime monitor
4. Database: pool alerts, slow query monitoring

## Phase 6: Go-Live

- [ ] All env vars in production
- [ ] Schema pushed to production Supabase
- [ ] RLS applied
- [ ] Payment products with live keys
- [ ] Webhook URLs → production
- [ ] DNS + SSL
- [ ] Email sender domain
- [ ] Auth redirect URLs
- [ ] npm run build — zero errors
- [ ] npm run type-check — zero errors

Prompt Engineering Reference

Anti-Hallucination via Context Anchoring

Every prompt forces the AI to read specific files before generating. Most effective hallucination technique.

❌ "Add a payments table to the database"
✅ "Read lib/db/schema/, then add a table following the subscriptions table pattern"

❌ "Create a new component"
✅ "Read frontend SKILL.md Section 1, then create using Crystal Card pattern"

❌ "Fix the auth issue"
✅ "Read debugging.md, check proxy.ts, trace from app/(auth)/login/page.tsx"

Think-Then-Act

Force analysis before code. Reduces hallucination 60-80%:

### THINK (reasoning first)
1. What files affected?
2. Dependencies?
3. What could break?

### ACT (code after thinking)
[Code here]

Quick Reference: File Paths

ResourcePath
Agent RootAGENTS.md
Claude RootCLAUDE.md
Backend Skill.agents/skills/backend/SKILL.md
Frontend Skill.agents/skills/frontend/SKILL.md
i18n Skill.agents/skills/i18n/SKILL.md
Schemalib/db/schema/ (barrel: lib/db/schema.ts)
Configlib/config.ts
Payment Adapterlib/payments/
Server Actionsapp/actions/
API Routesapp/api/
Auth Componentscomponents/auth/
Dashboardcomponents/dashboard/
Marketingcomponents/marketing/
Super-Admincomponents/super-admin/
UI (57)components/ui/
Locales (Frontend)locales/frontend/
Locales (Email)locales/emails/
SEOlib/seo/
Email Templateslib/email/templates/
Workflows (18).agents/workflows/
E2E Teststests/e2e/
Unit Teststests/unit/
RLS Policiessupabase/schema.sql

Copyright © 2026 Vibe44. Built with ❤️ by Scale with Alap.