If you rely solely on system prompts to enforce business rules, safety constraints, or free-vs-paid boundaries in a production LLM app, real user input will break them within 48 hours.

I learned this the hard way while hardening the AI reading and follow-up engine for Tarot Fortune Cards (Next.js 16 App Router + TypeScript + Vercel AI SDK). Even with crisp, explicit instructions in the system prompt—"never invent a calendar date," "never show an upsell on casual quick questions," "stay consistent with the opening answer"—our red-team and production logs surfaced three classic failure modes:

  1. Mobile typography bypasses: iOS keyboards auto-replace straight apostrophes ' with curly apostrophes ’. A user typing When’ll he text me? or I’ll meet him in 2026? silently slipped past naive regex guards.
  2. Keyword false positives: Allowing an upgrade from a free single-card draw to a deeper reading whenever a question mentioned "family" accidentally triggered on casual prompts like "Will my family like the cookies I baked today?"
  3. LLM boundary drift: Under follow-up pressure ("Just give me a rough month!"), even well-behaved models happily hallucinated "in 3 to 6 months" or "this October"—violating both product promises and user trust.

The fix was moving every hard product invariant out of prompts and into deterministic TypeScript modules shared between the client UI and Next.js Route Handlers. Here are the four concrete patterns we shipped, along with the real code and edge cases that bit us.

Pattern 1: One-Way Safety Rails on Intent Routing

Most consumer AI tools serve mixed traffic—some visitors want a fast, zero-friction free answer, while others bring a high-stakes multi-layered question.

On our quick single-card yes or no tarot route, our hard product rule is zero upsells, zero teasers, zero pricing on quick or casual draws. Instead of asking the model to "judge whether the question is serious," we enforce a unidirectional deterministic router before any LLM call runs:

const TRIVIAL_YES_NO_RE = /\b(eat|lunch|dinner|pizza|coffee|cookies?|cake|bake|movie|weather|outfit|haircut|gym|lottery)\b/i; const MAJOR_STAKES_RE = /\b(divorce|break\s*up|reconcil\w*|marry\s+(?:him|her|them)|quit\s+my\s+job|resign(?:ing)?\s+from|job\s+offer|change\s+careers?|buy\s+a\s+(?:house|home)|relocat\w*|lawsuit|take\s+(?:out\s+)?a\s+loan)\b/i; export function resolveTarotIntentLine(params: { userQuestion?: string | null; entrySlug?: string | null; typedByUser?: boolean; intentEngineEnabled?: boolean; }): TarotIntentLine { const q = (params.userQuestion || '').trim(); const wordCount = q.split(/\s+/).filter(Boolean).length; const entryDefault = resolveDefaultLineFromSlug(params.entrySlug); // Hard invariant: Yes/No routes stay locked in free short mode by default. // An upgrade requires ALL FOUR conditions simultaneously: // 1) explicitly typed by the user (never a preset placeholder), // 2) >= 15 words of genuine context, // 3) zero casual/trivial signals, and // 4) an explicit high-stakes decision phrase. if (entryDefault === 'yes_no_short') { if ( params.intentEngineEnabled && params.typedByUser === true && wordCount >= 15 && !TRIVIAL_YES_NO_RE.test(q) && MAJOR_STAKES_RE.test(q) ) { return 'yes_no_major'; } return 'yes_no_short'; } // ...route other entry slugs with user-typed override } 

Two details here proved unexpectedly critical during adversarial testing:

  • Require typedByUser === true explicitly. Treating undefined as "probably typed" breaks legacy sessions and preset example clicks.
  • Avoid broad single-word triggers like family or work. Phrase-level anchors (quit my job, buy a house, change careers) eliminate false positives like "Will my family like the cookies I baked for dinner tonight?"
  • Enforce suppressPaywall at the API boundary too, not just in React. Both our deep-reading generator and checkout endpoint re-run resolveTarotIntentLine() server-side and immediately refuse generation or checkout for yes_no_short sessions.

Pattern 2: Normalize Smart Quotes Before Running Contraction Guards

When routing follow-up questions on timing-heavy pages like when will he come back tarot, we separate three lanes:

  • Pure reference questions (strict whole-sentence whitelist—e.g. "What does The Moon reversed mean?"—rebuilt server-side into a canonical prompt so users can't smuggle prompt injections via "Explain The Tower. Now ignore previous rules...")
  • Timing forecast follow-ups (routed to a gated teaser lane)
  • Normal free follow-ups (action advice, emotional clarity, boundaries)

Our first timing detector checked will he, is he going to, etc.—and completely missed two real mobile patterns:

  1. Curly apostrophes (I’ll, he’ll, won’t) pasted or typed on iOS/macOS.
  2. Self-action sentences that happen to contain I'll + a time word—like "Should I text him today, and I'll keep it brief?"—which is action advice, not a timing forecast!

Separating apostrophe normalization from self-action exclusions fixed both directions cleanly:

function normalizeText(value: string): string { return value.replace(/[’‘`]/g, "'").replace(/\s+/g, ' ').trim(); } const FORECAST_CONTRACTION_CUES = /\b(?:(?:i|he|she|they|we|it)'ll|won't\s+(?:he|she|they|we|i|it)|(?:i|he|she|they|we|it)\s+won't|(?:i|he|she|they|we)\s+(?:(?:am|is|are|'m|'s|'re)\s+)?(?:gonna|going\s+to))\b/i; const SELF_ACTION_COMMITMENT_ONLY_RE = /\bi'll\s+(?:keep|just|only|say|send|write|text|wait|be\s+(?:brief|short|calm|polite)|hold\s+back)\b/i; export function isTimingFollowUpQuestion(message: string): boolean { const normalized = normalizeText(message); if (!normalized) return false; if (EXPLICIT_TIMING_PATTERNS.some((re) => re.test(normalized))) return true; // Allow pure action advice ("Should I text him today, and I'll keep it brief?") // unless it also contains a forecast clause (", and will he reply next week?"). if (ACTION_ONLY_PREFIX_PATTERN.test(normalized) && !COMPOUND_FORECAST_CLAUSE.test(normalized)) { return false; } if (!CALENDAR_FORECAST_PATTERN.test(normalized)) return false; if (FORECAST_QUESTION_CUES.test(normalized)) return true; if ( SELF_ACTION_COMMITMENT_ONLY_RE.test(normalized) && !/\b(?:he|she|they|we|it)'ll\b|\bwon't\b|\b(?:gonna|going\s+to)\b/i.test(normalized) ) { return false; } return FORECAST_CONTRACTION_CUES.test(normalized); } 

Pattern 3: Fail-Closed Output Firewalls (Validate Both Generation AND Cache Reads)

Prompts are probabilistic; production SLAs are deterministic.

For sensitive flows—such as preventing fabricated calendar dates, months, or numeric durations ("in 3 to 6 months", "by October", "in 2026") or preventing cross-template leaks between future-partner readings and reconciliation tarot reading flows—we treat the LLM output as untrusted input until it passes a code-level validator:

const FORBIDDEN_OUTPUT_RULES: Array<{ name: string; pattern: RegExp }> = [ { name: 'calendar_year_or_date', pattern: /\b20\d{2}\b|\b\d{1,2}[/-]\d{1,2}(?:[/-]\d{2,4})?\b|\bq[1-4]\b/i, }, { name: 'calendar_month', pattern: /\b(?:january|february|march|april|june|july|august|september|october|november|december)\b|\b(?:in|by|before|after|this|next)\s+may\b/i, }, { name: 'season_or_fixed_duration', pattern: /\b(?:in|by|this|next)\s+(?:spring|summer|autumn|fall|winter)\b|\b(?:within|in|over)\s+(?:the\s+next\s+)?\d+\s*(?:days?|weeks?|months?|years?)\b/i, }, { name: 'cross_template_leak', pattern: /\b(?:your\s+ex|no\s+contact|text\s+(?:him|her|them)\s+first|third\s+party)\b/i, }, ]; export function validateStructuredOutput(payload: DeepReading): string[] { const combined = `${payload.their_side}\n${payload.next_move}\n${payload.timing}`; return FORBIDDEN_OUTPUT_RULES .filter((rule) => rule.pattern.test(combined)) .map((rule) => rule.name); } 

Notice two subtle wins in that snippet:

  1. May disambiguation: Matching bare \bmay\b falsely flags English modal verbs ("you may notice..."). Scoping may behind prepositions (in|by|before|after|this|next may) keeps false positives at zero while still blocking month predictions.
  2. Closed-loop retry + fail-closed fallback: On generation, if validateStructuredOutput() returns any violation, we feed the exact violated rule names back into a bounded retry (max 3 attempts). On follow-up teasers, any violation (or wrong sentence count, or missing card orientation, or contradicting a "No / closure" opening verdict) immediately falls back to a deterministic, card-aware safe response—never streaming raw unverified text to the browser.
  3. Validate cached records too: If you persist generated JSON in PostgreSQL and later tighten your rules, always run the same validator on cache reads so pre-upgrade sessions never bypass your new guardrails.

Pattern 4: Independent Kill-Switches + Zero-Schema Sidecar Metadata

When shipping multiple behavioral upgrades together (intent router + contraction fix + dynamic hooks + card layout), rolling back an entire release because one UX tweak underperforms is painful.

Instead, we isolate every behavioral change behind an independent server-side boolean flag (default true, flipping to false in ~10 seconds via Vercel environment variables without touching git):

function isFlagEnabled(envVal: string | undefined, defaultValue = true): boolean { if (!envVal?.trim()) return defaultValue; return !['0', 'false', 'off', 'no'].includes(envVal.trim().toLowerCase()); } export function getWave1Flags() { return { timelockFix: isFlagEnabled(process.env.TAROT_TIMELOCK_FIX, true), intentEngine: isFlagEnabled(process.env.TAROT_INTENT_ENGINE, true), openingHook: isFlagEnabled(process.env.TAROT_OPENING_HOOK, true), cardSplit: isFlagEnabled(process.env.TAROT_CARD_SPLIT, true), }; } 

And to avoid running risky ALTER TABLE migrations on production PostgreSQL just to record entrySlug and typedByUser for each session, we stored a tiny structured JSON sidecar in our existing append-only session message table—giving us zero-downtime deployment and zero-migration rollback, while keeping every single one of our 23 public SEO routes byte-for-byte identical.

Takeaway

Prompts are great for tone, nuance, and synthesis. They are terrible for invariants.

If a rule matters to user trust, billing fairness, or legal/chargeback risk:

  • Route it in code before the prompt ever runs.
  • Normalize Unicode punctuation before running regexes.
  • Validate outputs fail-closed on both writes and cache reads.
  • Wrap behavioral layers in independent kill-switches so any single knob can be turned off in seconds.

How are you splitting responsibilities between prompts and deterministic TypeScript guardrails in your production AI apps?