<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Tarot Fortune Cards Engineering]]></title><description><![CDATA[Tarot Fortune Cards Engineering]]></description><link>https://tarotfortunecards.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 21:00:33 GMT</lastBuildDate><atom:link href="https://tarotfortunecards.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Zero-Backend Dual-Player SVG Radar Overlay & Fixing a 0.1126 localStorage CLS Bug in Next.js]]></title><description><![CDATA[How we built a zero-backend two-player SVG radar overlay via URL params and caught a 0.1126 returning-visitor localStorage CLS regression in Next.js.]]></description><link>https://tarotfortunecards.hashnode.dev/zero-backend-dual-player-svg-radar-overlay-fixing-a-0-1126-localstorage-cls-bug-in-next-js</link><guid isPermaLink="true">https://tarotfortunecards.hashnode.dev/zero-backend-dual-player-svg-radar-overlay-fixing-a-0-1126-localstorage-cls-bug-in-next-js</guid><category><![CDATA[Next.js]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[webdev]]></category><category><![CDATA[performance]]></category><dc:creator><![CDATA[tarotfortunecards]]></dc:creator><pubDate>Thu, 03 Dec 2026 03:26:17 GMT</pubDate><content:encoded><![CDATA[<p>Most interactive consumer quizzes get trapped in a classic engineering overbuild: spinning up user sessions, storing throwaway answers in Postgres, and shipping client banners that pass Lighthouse on cold load—only to fail Core Web Vitals for returning users.</p>
<p>While shipping three privacy-sensitive relationship micro-tools in Next.js App Router—a 5-pillar <a href="https://tarotfortunecards.art/couple-compatibility-quiz">couple compatibility quiz</a>, a weekly <a href="https://tarotfortunecards.art/does-he-still-love-me">behavioral relationship signal check</a>, and a local-only <a href="https://tarotfortunecards.art/should-i-break-up-with-him">private breakup clarity check</a>—we enforced two hard constraints:</p>
<ol>
<li><strong>Zero backend database state</strong> for quiz answers or two-person comparisons.</li>
<li><strong>Real headless Chrome Core Web Vitals checks (<code>CLS &lt;= 0.10</code>)</strong> across both <em>cold</em> and <em>returning</em> visits on <code>375×667</code>, <code>390×844</code>, and <code>1440×900</code>.</li>
</ol>
<p>That second constraint caught a subtle <code>CLS = 0.1126</code> bug that standard Lighthouse audits completely miss. Here is the architecture and every fix we shipped.</p>
<hr />
<h2>1. Zero-Backend Two-Player Comparison via Compact URL State</h2>
<p>For our 5-pillar partner radar (Communication Safety, Repair After Conflict, Emotional Presence, Trust &amp; Boundaries, and Shared Future Vision), Partner A answers 10 questions on their phone and invites Partner B to take the same 10 questions separately so both radar polygons overlay on one chart.</p>
<p>Instead of generating a database row and an expiring token, we serialize only the <strong>five summary scores (0–100)</strong>—never individual answers—into a tiny, strictly validated query string:</p>
<pre><code class="language-ts">export interface PartnerSummary {
  scores: [number, number, number, number, number];
  name: string;
}

export function encodePartnerInvite(
  baseUrl: string,
  scores: [number, number, number, number, number],
  rawName?: string
): string {
  const clamped = scores.map((n) =&gt; Math.max(0, Math.min(100, Math.round(n))));
  const params = new URLSearchParams();
  params.set('p', clamped.join('-'));
  const cleanName = (rawName || '').replace(/[^a-zA-Z0-9 '\-]/g, '').trim().slice(0, 18);
  if (cleanName) params.set('n', cleanName);
  return `${baseUrl}?${params.toString()}`;
}

export function parsePartnerInvite(searchParams: URLSearchParams): PartnerSummary | null {
  const raw = searchParams.get('p');
  if (!raw) return null;
  const parts = raw.split('-').map((v) =&gt; Number(v));
  if (parts.length !== 5 || parts.some((n) =&gt; !Number.isFinite(n) || n &lt; 0 || n &gt; 100)) {
    return null;
  }
  const cleanName = (searchParams.get('n') || '')
    .replace(/[^a-zA-Z0-9 '\-]/g, '')
    .trim()
    .slice(0, 18);
  return {
    scores: parts as [number, number, number, number, number],
    name: cleanName || 'Your Partner',
  };
}
</code></pre>
<p>Why this works far better than a database session for consumer tools:</p>
<ul>
<li><strong>Zero PII on the server</strong>: Partner A's individual answers never leave their device.</li>
<li><strong>Immutable links that never expire</strong>: If Partner B opens the text two days later, the overlay renders instantly with zero API latency.</li>
<li><strong>Deterministic perception-gap detection</strong>: As soon as Partner B finishes Question 10, the client computes <code>Math.abs(myScore[i] - partnerScore[i])</code> across all five axes and highlights the widest perception gap directly above the chart.</li>
</ul>
<hr />
<h2>2. Overlaying Two 5-Axis Polygons in ~20 Lines of Pure SVG</h2>
<p>No charting library bundle is needed for a crisp, mobile-safe 5-axis radar. Starting at <code>-Math.PI / 2</code> (12 o'clock) keeps axis 0 vertically centered:</p>
<pre><code class="language-ts">function polygonPoints(
  values: number[],
  cx: number,
  cy: number,
  radius: number
): string {
  const count = values.length;
  return values
    .map((val, idx) =&gt; {
      const angle = -Math.PI / 2 + (idx * 2 * Math.PI) / count;
      const r = (Math.max(0, Math.min(100, val)) / 100) * radius;
      const x = cx + r * Math.cos(angle);
      const y = cy + r * Math.sin(angle);
      return `${x.toFixed(1)},${y.toFixed(1)}`;
    })
    .join(' ');
}
</code></pre>
<p>Rendering Partner A's polygon with a dashed accent stroke underneath Partner B's filled gold polygon gives an immediate visual read of where the two perspectives align—and where one partner rates a pillar 35 points lower than the other.</p>
<hr />
<h2>3. The <code>0.1126</code> Returning-Visitor CLS Bug That Lighthouse Missed</h2>
<p>Our next two tools store a private snapshot in <code>localStorage</code> so users can run a 7-day real-life check and reopen their baseline next week—without creating an account or sending an email.</p>
<p>Here is the trap almost every React / Next.js app falls into when implementing a <em>"Welcome back — reopen your saved check"</em> banner:</p>
<pre><code class="language-tsx">// ❌ Looks harmless, scores CLS = 0.000 on cold load,
//    but hits CLS = 0.1126 for returning visitors!
export function ClarityWidget() {
  const [savedSnapshot, setSavedSnapshot] = useState&lt;Snapshot | null&gt;(null);

  useEffect(() =&gt; {
    setSavedSnapshot(readLocalSnapshot());
  }, []);

  return (
    &lt;section&gt;
      {savedSnapshot &amp;&amp; (
        &lt;div className="mb-4 p-3"&gt;
          Private check saved on {savedSnapshot.savedAt}
          &lt;button className="min-h-[44px]"&gt;Reopen saved check&lt;/button&gt;
        &lt;/div&gt;
      )}
      &lt;QuizForm /&gt;
    &lt;/section&gt;
  );
}
</code></pre>
<p>On a <strong>cold load</strong> (including PageSpeed Insights and standard Lighthouse runs), <code>localStorage</code> is empty, so <code>savedSnapshot</code> stays <code>null</code> and CLS is a spotless <strong><code>0.000</code></strong>.</p>
<p>On a <strong>returning visit</strong>, however:</p>
<ol>
<li>SSR HTML renders <code>&lt;QuizForm /&gt;</code> at <code>y = 0</code> inside the card.</li>
<li>React hydrates and runs <code>useEffect</code>.</li>
<li><code>savedSnapshot</code> flips from <code>null</code> to an object, injecting a <code>~66px</code> banner <strong>above</strong> <code>&lt;QuizForm /&gt;</code>.</li>
<li>Every interactive card below it shifts downward by <code>66px</code> with zero user input—spiking CLS to <strong><code>0.1126</code></strong> (above Google's <code>0.10</code> "Good" threshold) in real Chrome User Experience (CrUX) data!</li>
</ol>
<h3>How We Caught It Automatically</h3>
<p>In our headless Chrome CDP verification script, we inject a <code>PerformanceObserver</code> <em>before</em> navigation (<code>Page.addScriptToEvaluateOnNewDocument</code>) and deliberately run our second viewport pass <strong>reusing the same browser profile</strong> after clicking <em>"Save privately on this device"</em>:</p>
<pre><code class="language-js">await cdp.send('Page.addScriptToEvaluateOnNewDocument', {
  source: `
    window.__cls = 0;
    new PerformanceObserver((list) =&gt; {
      for (const entry of list.getEntries()) {
        if (!entry.hadRecentInput) window.__cls += entry.value;
      }
    }).observe({ type: 'layout-shift', buffered: true });
  `,
});
</code></pre>
<p>That warm-profile pass immediately flagged:</p>
<pre><code class="language-text">FAIL: CLS &lt;= 0.10 — cls=0.1126
</code></pre>
<h3>The Fix: Zero-Shift Placement Below the Primary Action</h3>
<p>Moving <code>{savedSnapshot ? &lt;ReopenBanner /&gt; : null}</code> to the <strong>bottom</strong> of the form container (right below the primary submit CTA) preserves the full <code>min-h-[44px]</code> accessible tap target while shifting <strong>zero</strong> above-the-fold elements on hydration:</p>
<ul>
<li><strong>Before</strong>: Returning desktop visit <code>CLS = 0.1126</code> (FAIL)</li>
<li><strong>After</strong>: First visit <code>CLS = 0.000</code>, returning visit <code>CLS = 0.005–0.0075</code> (PASS across all three viewports)</li>
</ul>
<hr />
<h2>4. Privacy-First UX Details Worth Auditing Before Launch</h2>
<p>When tools handle sensitive personal questions, small frontend choices matter as much as performance:</p>
<ul>
<li><strong>Match share controls to emotional context</strong>: A lighthearted couple radar thrives on 2-player invite links and downloadable cards; a private breakup reflection should ship <strong>zero</strong> public social share buttons—only local device storage.</li>
<li><strong>Accessible toggle semantics</strong>: Using <code>&lt;button type="button" role="checkbox" aria-checked={checked}&gt;</code> with <code>min-h-[44px]</code> gives keyboard accessibility and comfortable thumb taps on <code>375px</code> screens without fighting browser-native checkbox styling.</li>
<li><strong>Symmetric responsive grids</strong>: Always inspect desktop (<code>1440×900</code>) alongside mobile (<code>375×667</code>). A 4-card section accidentally styled with <code>lg:grid-cols-3</code> renders a lonely <code>3 + 1</code> orphan row on desktop—switching to <code>sm:grid-cols-2</code> fixes it in one class change.</li>
</ul>
<hr />
<h2>Takeaways</h2>
<ol>
<li><strong>Test returning visits, not just cold loads.</strong> Any <code>useEffect</code> reading <code>localStorage</code>, cookies, or auth state that prepends DOM above the fold will pass Lighthouse and silently degrade real-user CrUX CLS.</li>
<li><strong>Use URL query params as a zero-backend sync bus</strong> for lightweight multi-player comparisons—just clamp every numeric slot and strip untrusted characters strictly on parse.</li>
<li><strong>Automate real-browser screenshots + layout assertions</strong> across <code>375px</code>, <code>390px</code>, and <code>1440px</code>; our script caught a <code>16px</code> button target, a <code>3+1</code> orphan grid, and the <code>0.1126</code> warm-visit CLS spike in under 45 seconds before a single real user saw them.</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Zero-Backend Astronomy & 1080x1350 Canvas Share Cards in Next.js (Plus a 180° Geometry Bug We Caught)]]></title><description><![CDATA[How we built client-side Meeus moon-phase astronomy, fixed a 180° full-moon geometry bug, exported 1080x1350 PNG share cards, and kept mobile CLS at 0.]]></description><link>https://tarotfortunecards.hashnode.dev/zero-backend-astronomy-1080x1350-canvas-share-cards-in-next-js-plus-a-180-geometry-bug-we-caught</link><guid isPermaLink="true">https://tarotfortunecards.hashnode.dev/zero-backend-astronomy-1080x1350-canvas-share-cards-in-next-js-plus-a-180-geometry-bug-we-caught</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[webdev]]></category><category><![CDATA[canvas]]></category><dc:creator><![CDATA[tarotfortunecards]]></dc:creator><pubDate>Thu, 03 Dec 2026 03:24:08 GMT</pubDate><content:encoded><![CDATA[<p>When building interactive consumer micro-tools in Next.js, the fastest way to kill both profit margin and UX is putting simple deterministic math or share-card rendering behind a serverless function. Cold starts add 800ms–2s of spinner lag, Puppeteer/Satori image endpoints burn compute, and mobile users bounce before the result even appears.</p>
<p>While shipping three new client-side interactive tools on our site—a <a href="https://tarotfortunecards.art/moon-phase-soulmate-calculator">moon phase soulmate calculator</a>, a <a href="https://tarotfortunecards.art/soulmate-by-birth-date">soulmate by birth date calculator</a>, and an interactive <a href="https://tarotfortunecards.art/will-an-avoidant-come-back-after-no-contact">avoidant no-contact stage locator</a>—we moved <strong>100% of the calculation, SVG visualization, and <code>1080×1350</code> PNG share-card export into pure browser TypeScript</strong>.</p>
<p>Here are four real engineering lessons (including a subtle 180° geometry bug we only caught through headless Chrome visual screenshots).</p>
<hr />
<h2>1. Real Lunar Elongation in ~25 Lines of Pure TypeScript (No API Calls)</h2>
<p>Many birthday moon tools estimate lunar phases by taking <code>(daysSinceKnownNewMoon % 29.53)</code>. Because the Moon's orbit is elliptical (eccentricity ~0.0549), a naive synodic modulo can drift by <strong>12 to 18 hours</strong>, flipping dates near Quarter or Full Moons into the wrong phase.</p>
<p>Instead of calling a third-party ephemeris API, we implemented Jean Meeus's first-order solar and lunar anomaly corrections from Julian Day noon UTC in pure TypeScript:</p>
<pre><code class="language-ts">const DEG2RAD = Math.PI / 180;

function normDeg(deg: number): number {
  const m = deg % 360;
  return m &lt; 0 ? m + 360 : m;
}

function gregorianNoonToJulianDay(year: number, month: number, day: number): number {
  let y = year;
  let m = month;
  if (m &lt;= 2) {
    y -= 1;
    m += 12;
  }
  const a = Math.floor(y / 100);
  const b = 2 - a + Math.floor(a / 4);
  return (
    Math.floor(365.25 * (y + 4716)) +
    Math.floor(30.6001 * (m + 1)) +
    day +
    b -
    1524.5 +
    0.5 // 12:00 UTC
  );
}

export function computeLunarPhaseAngleDeg(
  year: number,
  month: number,
  day: number
): number {
  const jd = gregorianNoonToJulianDay(year, month, day);
  const t = (jd - 2451545.0) / 36525.0;
  const t2 = t * t;

  const d = normDeg(297.8501921 + 445267.1114034 * t - 0.0018819 * t2);
  const mSun = normDeg(357.5291092 + 35999.0502909 * t - 0.0001536 * t2);
  const mMoon = normDeg(134.9633964 + 477198.8675055 * t + 0.0087414 * t2);

  const dRad = d * DEG2RAD;
  const msRad = mSun * DEG2RAD;
  const mmRad = mMoon * DEG2RAD;

  const corr =
    6.289 * Math.sin(mmRad) -
    2.1 * Math.sin(msRad) +
    1.274 * Math.sin(2 * dRad - mmRad) +
    0.658 * Math.sin(2 * dRad) -
    0.214 * Math.sin(2 * mmRad) -
    0.11 * Math.sin(dRad);

  return normDeg(d + corr);
}
</code></pre>
<p>We verified this 25-line function against 6 historical NASA New and Full Moons across 1995–2026: every date landed within ~1–2 hours of exact syzygy, executes in <code>&lt; 0.1ms</code>, and requires zero external dependencies or network round trips.</p>
<hr />
<h2>2. The <code>angleA + angleB === 360°</code> Geometry Bug We Only Caught Visually</h2>
<p>In our first prototype of the combined moon visual, we scored "Full Moon complementarity" by checking how close <code>angleA + angleB</code> was to <code>360°</code> (mirroring Waxing vs. Waning).</p>
<p>That formula looked clean in unit tests—until we inspected an automated headless Chrome screenshot of two dates (<code>angleA = 53°</code> Waxing Crescent at 20% illumination, and <code>angleB = 307°</code> Waning Crescent at 20% illumination).</p>
<ul>
<li><code>53° + 307° = 360°</code>, so our formula rewarded it as a <strong>91% Full Moon Match</strong>.</li>
<li>Visually, superimposing two 20% crescents left a giant dark band down the middle (only 40% total illumination!).</li>
</ul>
<p>When do two lunar discs <strong>physically</strong> lock together into a seamless 100% Full Moon? When one is Waxing at elongation <code>θ</code> (lit on the right limb, illumination <code>(1 - cos θ) / 2</code>) and the other is Waning at <code>θ + 180°</code> (lit on the left limb, illumination <code>(1 + cos θ) / 2</code>):</p>
<pre><code class="language-text">(1 - cos θ) / 2  +  (1 + cos θ) / 2  =  1.0 (100% Full Moon)
</code></pre>
<p>That means exact opposition—<code>angularDistance(angleA, angleB) === 180°</code>—NOT <code>angleA + angleB === 360°</code>:</p>
<pre><code class="language-ts">const rawDiff = Math.abs(angleA - angleB);
const angularDiff = rawDiff &gt; 180 ? 360 - rawDiff : rawDiff; // 0..180
const oppositionDelta = Math.abs(180 - angularDiff); // 0 = exact Full Moon complement
const fullMoonFitPct = Math.round(
  Math.max(40, Math.min(100, 100 - (oppositionDelta / 180) * 60))
);
</code></pre>
<p>Once fixed, a <code>53°</code> Waxing Crescent (20%) pairs with a <code>233°</code> Waning Gibbous (80%) to produce a visually seamless 99% Full Moon disc—and the numeric score finally matches what the user's eyes see on screen.</p>
<hr />
<h2>3. Exporting <code>1080×1350</code> PNG Share Cards Purely with HTML5 Canvas</h2>
<p>Every social-ready tool benefits from a downloadable vertical <code>4:5</code> (<code>1080×1350</code>) PNG card. Running <code>@vercel/og</code> or headless Chrome on the server for dynamic cards adds latency and billing overhead, whereas an offscreen <code>&lt;canvas&gt;</code> generates a crisp ~800 KB retina PNG in under 40ms right on the user's phone:</p>
<pre><code class="language-ts">function downloadCanvasCard(canvas: HTMLCanvasElement, filename: string) {
  const dataUrl = canvas.toDataURL('image/png');
  const link = document.createElement('a');
  link.href = dataUrl;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
</code></pre>
<p>Two practical tips that saved us real bugs on mobile Safari and Chrome:</p>
<ol>
<li><strong>Always write a deterministic word-wrapper for Canvas text</strong> (<code>ctx.measureText(candidate).width &lt;= maxWidth</code> with an explicit <code>maxLines</code> cap) so long headlines or archetype subtitles never bleed across the border frame.</li>
<li><strong>Use URL query params (<code>?d=1997-08-14</code> or <code>?a=1997-04-11&amp;b=1996-09-01</code>) instead of database IDs</strong> for shareable tool results. Anyone opening the copied link gets an instant, zero-API hydration of the exact result with zero storage cost and zero privacy risk.</li>
</ol>
<hr />
<h2>4. Keeping Mobile <code>CLS = 0.000</code> Across Dynamic Result States</h2>
<p>More than 80% of our real traffic is on mobile (<code>375×667</code> and <code>390×844</code>). Interactive tools frequently suffer from Cumulative Layout Shift (CLS) and clipped scroll targets when results mount dynamically. Four small CSS/React habits brought our real-Chrome mobile CLS down to <code>0.000</code>:</p>
<ul>
<li><strong>Reserve explicit stage heights</strong> (e.g., <code>h-[116px]</code> wrapper around custom SVGs and medallions) so visual discs align horizontally and never jump while fonts settle.</li>
<li><strong>Add <code>scroll-mt-20 sm:scroll-mt-24</code> to every <code>scrollIntoView</code> result container</strong> so fixed top navigation bars never slice across the top badge when auto-scrolling to a newly revealed result.</li>
<li><strong>Avoid fake "Calculating..." spinners on pure frontend math.</strong> Rendering results synchronously on click removes an entire state transition that causes layout thrash and impatient double-taps.</li>
<li><strong>Automate real-Chrome visual QA across <code>375×667</code>, <code>390×844</code>, and <code>1440×900</code> via CDP</strong> before every merge—checking <code>PerformanceObserver</code> CLS, <code>scrollWidth - innerWidth === 0</code>, touch-target height <code>&gt;= 44px</code>, and actually inspecting the rendered PNG screenshots for subtle ring-padding or fold-clipping issues.</li>
</ul>
<hr />
<h3>Wrapping Up</h3>
<p>Moving astronomy calculations, stage locators, and retina share-card rendering completely to the browser gave us instant 0ms interaction, zero serverless image costs, <code>CLS = 0.000</code> on mobile, and clean shareable URLs that double as organic entry points.</p>
<p>If you've built client-side Canvas exporters or hit unexpected geometry edge cases in SVG/Canvas tools, I'd love to hear how you handled them in the comments!</p>
]]></content:encoded></item><item><title><![CDATA[Why LLMs Still Write Needy Copy & Leak Paid Tiers — 3 Deterministic TypeScript Guardrails We Shipped]]></title><description><![CDATA[How we stopped an LLM from writing needy relationship copy, fixed subordinate-clause regex stripping, and isolated single-unlock vs pass tiers in Next.js.]]></description><link>https://tarotfortunecards.hashnode.dev/why-llms-still-write-needy-copy-leak-paid-tiers-3-deterministic-typescript-guardrails-we-shipped</link><guid isPermaLink="true">https://tarotfortunecards.hashnode.dev/why-llms-still-write-needy-copy-leak-paid-tiers-3-deterministic-typescript-guardrails-we-shipped</guid><category><![CDATA[AI]]></category><category><![CDATA[llm]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[Next.js]]></category><dc:creator><![CDATA[tarotfortunecards]]></dc:creator><pubDate>Sun, 29 Nov 2026 08:42:37 GMT</pubDate><content:encoded><![CDATA[<p>When you ship an AI consumer product with paid tiers, the hardest bugs to eliminate are not crashes—they are subtle output regressions that quietly erode user trust right before checkout.</p>
<p>While expanding our interactive tarot web app with dedicated relationship flows—including our <a href="https://tarotfortunecards.art/ace-of-cups-as-feelings">Ace of Cups as feelings</a>, <a href="https://tarotfortunecards.art/the-devil-as-feelings">The Devil as feelings</a>, and <a href="https://tarotfortunecards.art/is-he-cheating-tarot">is he cheating tarot</a> pages—we ran a 14-scenario live audit across free readings, single-reading unlocks, and 30-day passes. That pass uncovered three recurring engineering problems that prompt edits alone could not reliably solve:</p>
<ol>
<li>The model kept generating overly needy message scripts even when told to stay calm.</li>
<li>Our mid-sentence refusal stripper left broken subordinate clauses (<code>"If you're wondering..."</code>) dangling in Sentence 1.</li>
<li>Our paywall copy accidentally leaked relationship-specific perks onto career and general readings.</li>
</ol>
<p>Here are the three deterministic TypeScript guardrails we shipped in Next.js to close every one of those gaps.</p>
<hr />
<h2>1. Why Prompting "Match Their Emotional Temperature" Fails Without a Validator</h2>
<p>One of our highest-value paid sections gives users a grounded, low-pressure message draft when they are deciding whether to text someone during silence or uncertainty.</p>
<p>Even with detailed prompt instructions asking the model to match the other person's emotional temperature, fast models reliably fell back to relationship-blog clichés inside quoted drafts:</p>
<ul>
<li><em>"I've been thinking about you lately..."</em></li>
<li><em>"Had a really good time with you, just checking in..."</em></li>
<li><em>"I miss feeling close to you..."</em></li>
</ul>
<p>When someone hasn't heard back in two weeks, opening with <em>"I've been thinking about you"</em> feels needy and immediately breaks the credibility of the advice.</p>
<h3>The Fix: Deterministic Quoted-Script Validation + Targeted Retry</h3>
<p>Instead of piling more adjectives into the system prompt, we built a lightweight deterministic validator that inspects <strong>only quoted message strings</strong> inside the generated section and flags high-frequency needy clichés before the response reaches the client:</p>
<pre><code class="language-ts">const QUOTED_SCRIPT_RE = /["“]([^"”]{10,220})["”]/g;

const NEEDY_SCRIPT_CLICHE_RE =
  /\b(i['’]ve\s+been\s+thinking\s+about\s+you|thinking\s+of\s+you\s+lately|how\s+things\s+ended|had\s+a\s+really\s+good\s+time\s+with\s+you|i\s+miss\s+feeling\s+close\s+to\s+you)\b/i;

export function hasNeedyScriptCliche(text: string): boolean {
  for (const match of text.matchAll(QUOTED_SCRIPT_RE)) {
    const quoted = match[1] ?? '';
    if (NEEDY_SCRIPT_CLICHE_RE.test(quoted)) {
      return true;
    }
  }
  return false;
}
</code></pre>
<p>Scoping the regex strictly to quoted dialogue matters: the narrator is still allowed to discuss <em>"how things ended"</em> in analytical prose, while the copy-pasteable text message itself is guaranteed to stay grounded and low-pressure. When <code>hasNeedyScriptCliche</code> triggers, our server runs a single focused repair pass with the exact offending phrase rejected.</p>
<hr />
<h2>2. The Subordinate-Clause Bug in Refusal Lead-In Stripping</h2>
<p>Sometimes an LLM answers a deep follow-up question by starting Sentence 1 with a robotic meta-disclaimer:</p>
<blockquote>
<p><em>"The cards can't reveal his exact private thoughts, what they show is a pull toward caution."</em></p>
</blockquote>
<p>Or even trickier, a refusal embedded after a conditional clause:</p>
<blockquote>
<p><em>"If you're wondering what happens next, tarot can't predict exact dates — what the cards point to is a shift once the current tension settles."</em></p>
</blockquote>
<p>Our first deterministic sanitizer tried to slice off the disclaimer prefix and keep the insight after <code>"what they show is"</code>. On plain sentences, that worked cleanly. On the second example, however, stripping from the middle of Sentence 1 left a broken sentence fragment behind:</p>
<blockquote>
<p><em>"If you're wondering what happens next, a shift once the current tension settles."</em></p>
</blockquote>
<h3>The Fix: Guard Against Orphaned Subordinate Clauses Before Slicing</h3>
<p>Before stripping a mid-sentence refusal lead-in, we check whether the surviving prefix starts with a subordinate conjunction (<code>If</code>, <code>When</code>, <code>While</code>, <code>Because</code>, <code>Although</code>, <code>Since</code>, <code>Unless</code>). If it does, we discard the incomplete leading clause cleanly and promote the complete main insight to Sentence 1:</p>
<pre><code class="language-ts">const SUBORDINATE_CLAUSE_START_RE =
  /^(?:if|when|while|because|although|though|since|unless|once|whether)\b/i;

export function stripColdWaterLeadIn(text: string): string {
  const refusalIdx = text.search(
    /\b(?:the\s+cards?\s+can(?:not|'t)|tarot\s+can(?:not|'t)|i\s+can(?:not|'t)\s+(?:read|see\s+inside|predict))\b/i
  );
  if (refusalIdx === -1 || refusalIdx &gt; 180) return text;

  const prefix = text.slice(0, refusalIdx).trim().replace(/[,;:\-—]+$/, '').trim();
  const pivotMatch = text
    .slice(refusalIdx)
    .match(/\b(?:what\s+(?:they|the\s+cards?)\s+(?:do\s+|actually\s+)?(?:show|point\s+to|reveal)\s+is|instead[,\s]+|here[,\s]+)\s*/i);

  if (!pivotMatch || pivotMatch.index === undefined) return text;

  const remainder = text.slice(refusalIdx + pivotMatch.index + pivotMatch[0].length).trim();
  if (!remainder) return text;

  const capitalized = remainder.charAt(0).toUpperCase() + remainder.slice(1);

  // Drop orphaned leading subordinate clauses instead of producing broken grammar
  if (!prefix || SUBORDINATE_CLAUSE_START_RE.test(prefix)) {
    return capitalized;
  }

  return `${prefix}. ${capitalized}`;
}
</code></pre>
<p>Our adversarial test suite caught this exact edge case during pre-merge review—turning a silent grammatical break into a crisp, direct opening sentence every time.</p>
<hr />
<h2>3. Enforcing Tier Quotas &amp; Intent-Isolated Checkout Copy Server-Side</h2>
<p>As our product grew from a single reading unlock (<code>$4.99</code>) to a 30-day unlimited pass (<code>$12.99</code>), we ran into two classic SaaS architecture mistakes:</p>
<ol>
<li><strong>Blurred quota boundaries</strong>: Single-reading unlocks initially shared the same generous follow-up quota as the 30-day pass, leaving users with no concrete reason to upgrade even after asking 10+ follow-ups.</li>
<li><strong>Cross-intent benefit leaks</strong>: Checkout bullets written for relationship users (<em>"decode their mixed texts &amp; draft your next reply"</em>) accidentally surfaced on career and general guidance checkout cards.</li>
</ol>
<h3>The Fix: Explicit Tier Resolution + Pure Intent Benefit Map</h3>
<p>We separated tier entitlement resolution on the backend so quota enforcement never relies on client flags:</p>
<pre><code class="language-ts">export type UnlockTier = 'free' | 'single' | 'pass';

export const SINGLE_UNLOCK_FOLLOW_UPS = 5;
export const PASS_UNLOCK_FOLLOW_UPS = 100;

export function resolveFollowUpCap(tier: UnlockTier): number {
  if (tier === 'pass') return PASS_UNLOCK_FOLLOW_UPS;
  if (tier === 'single') return SINGLE_UNLOCK_FOLLOW_UPS;
  return 0;
}
</code></pre>
<p>And on the checkout UI side, every paywall surface reads from a single pure intent map (<code>getIntentCheckoutPack(intent)</code>) with strict domain boundaries:</p>
<pre><code class="language-ts">export type ReadingIntent =
  | 'ex_reconciliation'
  | 'cheating_trust'
  | 'ambiguous_crush'
  | 'feelings_clarity'
  | 'career'
  | 'soulmate'
  | 'general';

const LOVE_TEXT_DECODE_INTENTS = new Set&lt;ReadingIntent&gt;([
  'ex_reconciliation',
  'cheating_trust',
  'ambiguous_crush',
  'feelings_clarity',
]);

export function supportsLoveTextDecoding(intent: ReadingIntent): boolean {
  return LOVE_TEXT_DECODE_INTENTS.has(intent);
}
</code></pre>
<p>Both the <code>$4.99</code> card and the <code>$12.99</code> upgrade card check <code>supportsLoveTextDecoding(intent)</code> before rendering text-decoding perks. A career or general user sees career/decision clarity perks—never a stray bullet about decoding an ex's mixed messages.</p>
<hr />
<h2>Key Takeaway</h2>
<p>Prompts are great for nuance, empathy, and creative synthesis. They are terrible for hard invariants—whether that invariant is <em>"never put needy clichés inside a suggested text message"</em>, <em>"never leave a broken <code>If...</code> clause after stripping a refusal"</em>, or <em>"never promise love-text decoding on a career checkout card"</em>. Moving those invariants into tiny, unit-tested TypeScript functions gave us predictable production behavior without slowing down the reading flow.</p>
<hr />
<h2>Frequently Asked Questions</h2>
<h3>Why validate quoted text separately instead of running a regex over the full LLM output?</h3>
<p>Analytical prose often needs to reference phrases like <em>"how things ended"</em> or <em>"thinking about you"</em> to describe a user's situation accurately. Scoping the cliché filter strictly to quoted speech blocks needy message drafts without causing false positives in the rest of the reading.</p>
<h3>Why handle refusal stripping in code if the prompt already forbids meta-disclaimers?</h3>
<p>Smaller, lower-latency models still emit occasional refusal lead-ins under edge-case follow-up phrasing. A deterministic post-processor acts as a fail-closed safety net so users never see cold robotic disclaimers—even on the 3% of responses where the prompt slips.</p>
<h3>How should multi-tier AI quotas be enforced in Next.js?</h3>
<p>Always derive the active entitlement tier (<code>free</code>, <code>single</code>, or <code>pass</code>) from verified server-side order/pass records in the API route before invoking the LLM, and return structured cap metadata so the UI can cleanly transition from the single-unlock limit to an upgrade card.</p>
]]></content:encoded></item><item><title><![CDATA[Why a Single Few-Shot Example Made Our LLM Hallucinate User History — And 3 Prompt & Regex Bugs We Fixed]]></title><description><![CDATA[How one few-shot example caused LLM hallucinations, why negative prompt rules backfire, and 3 TypeScript regex bugs caught by 256 adversarial tests.]]></description><link>https://tarotfortunecards.hashnode.dev/why-a-single-few-shot-example-made-our-llm-hallucinate-user-history-and-3-prompt-regex-bugs-we-fixed</link><guid isPermaLink="true">https://tarotfortunecards.hashnode.dev/why-a-single-few-shot-example-made-our-llm-hallucinate-user-history-and-3-prompt-regex-bugs-we-fixed</guid><category><![CDATA[AI]]></category><category><![CDATA[llm]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[webdev]]></category><dc:creator><![CDATA[tarotfortunecards]]></dc:creator><pubDate>Sun, 29 Nov 2026 04:34:35 GMT</pubDate><content:encoded><![CDATA[<p>When you ship an LLM-powered product to real users, the bugs that destroy trust rarely look like 500 errors. They look like fluent, confident sentences that quietly fabricate a fact the user never mentioned—or misroute a nuanced question into the wrong UX flow.</p>
<p>While expanding our interactive tarot app with focused relationship pages—including our <a href="https://tarotfortunecards.art/will-he-contact-me-tarot">will he contact me tarot</a> and <a href="https://tarotfortunecards.art/does-he-miss-me-tarot">does he miss me tarot</a> flows—we ran an 11-scenario live E2E pass alongside 256 adversarial unit tests. That review exposed four subtle bugs in our TypeScript routing and LLM prompting stack. None of them threw an exception, yet every single one hurt output quality.</p>
<p>Here is what broke, why it happened, and the exact fixes that held up in production.</p>
<hr />
<h2>Why Did Our LLM Keep Inventing a "Warm Message" the User Never Mentioned?</h2>
<p>During E2E testing on our silence-focused reading flow, we sent a minimal prompt with zero backstory:</p>
<blockquote>
<p><code>"Will he contact me again after this silence?"</code></p>
</blockquote>
<p>Our model opened with:</p>
<blockquote>
<p><em>"The pull you're feeling is between a short, warm contact that came out of nowhere and a silence that followed it..."</em></p>
</blockquote>
<p>Wait—what warm contact? The user never mentioned receiving a message. In any personalized AI reading or coaching app, asserting an unmentioned concrete event immediately breaks credibility if it never happened.</p>
<h3>The Root Cause: Few-Shot Example Leakage</h3>
<p>We had explicitly written <code>"Never invent events or backstory they did not mention"</code> in our system prompt. So why did the model ignore it?</p>
<p>Because ten lines earlier, we had included this "good style" few-shot example to encourage emotionally specific openings:</p>
<pre><code class="language-text">Example GOOD opening:
"That brief text wasn't random, and the silence right after feels like someone cracking a door an inch..."
</code></pre>
<p>Even when a rule forbids inventing facts, <strong>models imitate concrete nouns inside positive few-shot examples far more strongly than they obey abstract negative instructions</strong>. Because our example started with <code>"That brief text"</code>, the model kept injecting a phantom <code>"warm contact"</code> or <code>"warm message"</code> whenever the user prompt only mentioned <code>"silence"</code>.</p>
<h3>The Fix: Event-Free Examples + Inclusive Framing</h3>
<p>We replaced every concrete unmentioned event in our few-shot examples with purely emotional tension and added an explicit zero-invented-event contract:</p>
<pre><code class="language-ts">// Before (leaked phantom "brief text" into unrelated silence questions):
// "That brief text wasn't random, and the silence right after feels like..."

// After (zero unmentioned events, high emotional specificity):
const ZERO_INVENTED_EVENT_RULE = `
- ZERO-INVENTED-EVENT RULE: Never assert a specific past event (a brief text,
  warm message, phone call, meetup, or timeframe) unless the user wrote it.
  If the question is brief, stay strictly on the tension they named or use
  inclusive phrasing ("whether this quiet followed a warm stretch or drifted in").
- Example GOOD opening:
  "The hardest part of this silence isn't just not hearing from him — it's
  feeling like the door stayed cracked an inch without ever giving you a straight answer."
`;
</code></pre>
<p>Re-running the exact same bare silence scenarios eliminated the fabricated <code>"warm message"</code> completely while keeping the opening sharp and specific.</p>
<hr />
<h2>Why Did Banning "I Cannot Read Minds" Make the Model Output That Exact Disclaimer?</h2>
<p>On follow-up questions like <em>"What does he regret most about how things ended?"</em>, the model frequently opened Sentence 1 with a cold refusal:</p>
<blockquote>
<p><em>"The cards can't reveal his private regrets, and I can't see inside his head. What they do show is..."</em></p>
</blockquote>
<p>Our first patch tried to forbid those exact phrases and explain the fallback:</p>
<pre><code class="language-text">STRICTLY FORBID "I can't see inside his head" or "I cannot read his mind".
If you note that tarot reads patterns rather than verbatim thoughts, tuck that boundary in the middle.
</code></pre>
<p>That barely cut the rate in half! On our next live test on the follow-up lane, the model <em>still</em> opened with <code>"The cards can't reveal his private regrets, but..."</code>.</p>
<h3>The Root Cause: The Pink-Elephant Effect in System Prompts</h3>
<p>Repeating the exact phrasing you do not want—especially paired with an <code>"if you note that..."</code> escape hatch—keeps those disclaimer concepts active in the model's context window. Small fast models like Haiku treat <code>"if you note X"</code> as permission to keep outputting a paraphrased version of X.</p>
<h3>The Fix: Delete the Disclaimer Priming Completely</h3>
<p>We deleted every mention of mind-reading and limitations from the follow-up system prompt, replacing it with a purely positive structural instruction:</p>
<pre><code class="language-ts">const FOLLOWUP_OPENER_RULE = `
Cut dry robotic openings ("The cards show...") and skip all meta-disclaimers
about tarot's limits. Always open Sentence 1 directly with the sharpest
emotional or behavioral truth the drawn cards expose for what they just asked —
vary your phrasing naturally and anchor straight into the exact drawn card and position.
`;
</code></pre>
<p>After removing the negative priming, 4 out of 4 live follow-up tests opened straight into grounded card insights with zero cold-water disclaimers.</p>
<hr />
<h2>How Did 256 Adversarial Tests Catch Two TypeScript Intent-Routing Regex Bugs?</h2>
<p>Our backend classifies user questions deterministically in TypeScript before calling the LLM so each intent line gets its own prompt, follow-up suggestions, and safety guardrails (for instance, keeping trivial yes/no queries completely free of upsells).</p>
<p>Everything passed our standard 200+ happy-path tests—until an adversarial sweep flagged <strong>28 failures</strong> across two real user phrasings:</p>
<ol>
<li><strong>Precedence bug</strong>: <code>"Is he cheating on me with his ex?"</code> routed to <code>ex_reconciliation</code> instead of <code>cheating_trust</code> because our bare <code>\bex\b</code> matcher ran before our cheating matcher.</li>
<li><strong>Morphology &amp; punctuation bug</strong>: <code>"After our break-up, will he contact me?"</code> and <code>"We have broken up. Does he miss me?"</code> missed <code>break\s*up|broke\s+up</code> completely because of the hyphen (<code>break-up</code>) and past participle (<code>broken up</code>).</li>
</ol>
<h3>The Fix: Explicit Precedence + Override Guard + Flexible Word Forms</h3>
<pre><code class="language-ts">const EX_QUESTION_RE =
  /\b(ex|break[\s-]*up|brok(?:e|en)\s+up|reconcil\w*|get\s+back\s+together|come\s+back|no\s+contact)\b/i;

const CHEATING_QUESTION_RE =
  /\b(cheat(?:ing|ed)?|unfaithful|affair|infidelity|seeing\s+someone\s+else)\b/i;

// Keep "My ex cheated on me, will he come back?" in ex_reconciliation,
// while routing "Is he cheating on me with his ex?" to cheating_trust.
const EX_RECONCILE_OVERRIDE_RE =
  /\b(come\s+back|coming\s+back|get\s+back\s+together|reconcil\w*|return\s+to\s+me)\b/i;

export function classifyLoveQuestion(q: string) {
  if (CHEATING_QUESTION_RE.test(q) &amp;&amp; !EX_RECONCILE_OVERRIDE_RE.test(q)) {
    return 'cheating_trust';
  }
  if (EX_QUESTION_RE.test(q)) {
    return 'ex_reconciliation';
  }
  return 'ambiguous_crush';
}
</code></pre>
<p>That four-line precedence guard separates <code>"Is he cheating on me with his ex?"</code> (<code>cheating_trust</code>) from <code>"My ex cheated on me, will he come back?"</code> (<code>ex_reconciliation</code>) cleanly with zero extra LLM calls.</p>
<hr />
<h2>Why Did Naive Sentence Splitting Truncate Teasers Mid-Quote?</h2>
<p>To display a clean one-sentence preview for each section of a structured LLM report, we had a helper that extracted the first sentence with a classic regex:</p>
<pre><code class="language-ts">// Buggy: splits right at the '?' inside quoted speech!
const sentences = cleaned.match(/[^.!?]+[.!?]/g);
</code></pre>
<p>In live testing, the model produced:</p>
<blockquote>
<p><code>Silence protects you now, because texting carries the question "do you still want me?" before he is ready.</code></p>
</blockquote>
<p>Our helper sliced right after <code>me?</code>, rendering an awkward broken fragment with an unclosed quote:</p>
<blockquote>
<p><code>Silence protects you now, because texting carries the question "do you still want me?</code></p>
</blockquote>
<h3>The Fix: Quote-Aware Sentence Matching</h3>
<p>Matching quoted spans atomically before checking sentence-ending punctuation fixed the truncation in one line:</p>
<pre><code class="language-ts">export function firstSentence(text: string): string {
  const cleaned = text.trim().replace(/\s+/g, ' ');
  const sentences = cleaned.match(/(?:[^.!?"“”]|"[^"]*"|“[^”]*”)+[.!?]["”']?/g);
  if (!sentences || sentences.length === 0) {
    return cleaned.slice(0, 160).trim();
  }
  const first = sentences[0].trim();
  if (first.length &lt; 60 &amp;&amp; sentences.length &gt; 1) {
    const combined = `${first} ${sentences[1].trim()}`;
    return combined.length &lt;= 240 ? combined : first;
  }
  return first;
}
</code></pre>
<hr />
<h2>Frequently Asked Questions</h2>
<h3>How do you stop an LLM from hallucinating details that appear in few-shot examples?</h3>
<p>Audit every positive few-shot example in your system prompt and strip out domain nouns you don't want repeated (such as specific messages, dates, or events). Models treat concrete details inside few-shot examples as templates to copy, even when a separate rule tells them not to invent backstory.</p>
<h3>Why do negative prompt rules ("never say X") sometimes increase the chance of X appearing?</h3>
<p>Spelling out the exact phrase you want to avoid—especially alongside conditional phrasing like <em>"if you mention X, put it at the end"</em>—primes those tokens in the model's attention window. Replacing negative rules with positive structural examples and removing disclaimer vocabulary altogether works much more reliably.</p>
<h3>Should intent classification use deterministic TypeScript regexes or an LLM router?</h3>
<p>For latency-sensitive routes and strict safety/paywall boundaries, deterministic TypeScript matchers run in microseconds, cost $0, and are 100% unit-testable against adversarial edge cases. The key is testing compound phrasings (like overlapping keywords and hyphenated variants) rather than only single-intent happy paths.</p>
]]></content:encoded></item><item><title><![CDATA[Why Tailwind v4's translate Property Broke Our 22-Card Interactive Fan — And How We Cut Draw API Latency by 60%]]></title><description><![CDATA[Why Tailwind v4 breaks transition-[transform] on translate/scale utilities, and how Promise.all + TTL caching cut Next.js API latency 60%.]]></description><link>https://tarotfortunecards.hashnode.dev/why-tailwind-v4-s-translate-property-broke-our-22-card-interactive-fan-and-how-we-cut-draw-api-latency-by-60</link><guid isPermaLink="true">https://tarotfortunecards.hashnode.dev/why-tailwind-v4-s-translate-property-broke-our-22-card-interactive-fan-and-how-we-cut-draw-api-latency-by-60</guid><category><![CDATA[Tailwind CSS]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[web performance]]></category><category><![CDATA[CSS]]></category><dc:creator><![CDATA[tarotfortunecards]]></dc:creator><pubDate>Sun, 29 Nov 2026 02:07:01 GMT</pubDate><content:encoded><![CDATA[<p>When we upgraded our Next.js 16 app to <strong>Tailwind CSS v4</strong>, almost everything worked out of the box—except one interactive component that suddenly felt janky.</p>
<p>On <a href="https://tarotfortunecards.art">Tarot Fortune Cards</a>, visitors draw cards from an overlapping 22-card fan before receiving a reading. After moving to Tailwind v4, hovering and selecting a card snapped abruptly instead of gliding smoothly—and every card click still took over a second to settle.</p>
<p>Root-causing that single interaction uncovered two completely separate bugs: a <strong>Tailwind v4 CSS compilation change</strong> that quietly breaks <code>transition-[transform]</code>, and a <strong>6-query database waterfall</strong> hiding inside a tiny Next.js Route Handler. Here is how we fixed both in under an hour.</p>
<hr />
<h2>Bug 1: Why <code>transition-[transform]</code> Stops Animating <code>-translate-y-5</code> in Tailwind v4</h2>
<p>In Tailwind v3, utility classes like <code>-translate-y-5</code> and <code>scale-[1.05]</code> compiled down to CSS custom properties inside a single <code>transform:</code> declaration:</p>
<pre><code class="language-css">/* Tailwind v3 output */
.hover\:-translate-y-5:hover {
  --tw-translate-y: -1.25rem;
  transform: translate(var(--tw-translate-x), var(--tw-translate-y)) scaleX(...) scaleY(...);
}
</code></pre>
<p>So writing <code>transition-[transform,opacity]</code> animated hover lifts and scale jumps seamlessly.</p>
<p>In <strong>Tailwind v4</strong>, translate and scale utilities compile to the modern <strong>individual CSS transform properties</strong> (<code>translate</code> and <code>scale</code>), <em>not</em> the legacy <code>transform</code> shorthand:</p>
<pre><code class="language-css">/* Tailwind v4 output */
.group:hover .group-hover\:-translate-y-5 {
  translate: var(--tw-translate-x) -1.25rem;
}
.group:hover .group-hover\:scale-\[1\.05\] {
  scale: 1.05 1.05;
}
</code></pre>
<p>Because <code>translate</code> and <code>scale</code> are distinct CSS properties from <code>transform</code>, an explicit <code>transition-[transform,opacity,border-color,box-shadow]</code> <strong>completely ignores them</strong>! The card teleports instantly on hover and snaps back abruptly on click.</p>
<h3>The Fix</h3>
<p>List <code>translate</code> and <code>scale</code> explicitly in both <code>transition-[...]</code> and <code>will-change-[...]</code>:</p>
<pre><code class="language-tsx">&lt;div
  className={`relative h-full w-full overflow-hidden rounded-[14px] border
    will-change-[translate,scale,opacity]
    transition-[transform,translate,scale,opacity,border-color,box-shadow]
    duration-300 ease-out ${
      isRemoved
        ? '-translate-y-[116px] scale-[0.94] opacity-0'
        : isClicked
          ? '-translate-y-[84px] scale-[1.08] opacity-100'
          : 'translate-y-0 scale-100 opacity-100 group-hover:-translate-y-5 group-hover:scale-[1.05]'
    }`}
&gt;
</code></pre>
<p>Keep <code>transform</code> in the transition list too if you combine Tailwind utilities with inline <code>style={{ transform: rotate(...) }}</code> for fan arc positioning. The instant we added <code>translate,scale</code>, every card hover, lift, and fade-out returned to silky 60fps.</p>
<p><em>(If you want to feel the live difference, try hovering and pulling a card on our interactive <a href="https://tarotfortunecards.art/is-he-thinking-about-me-tarot">is he thinking about me tarot</a> draw deck.)</em></p>
<hr />
<h2>Bug 2: The 6-Query Database Waterfall Inside <code>/api/reading/draw</code></h2>
<p>Even after the CSS glide was smooth, clicking a card still lagged behind the animation. Checking server timing on our serverless PostgreSQL route (<code>POST /api/tarot/reading/draw</code>) showed why: every single click was running <strong>6 sequential database roundtrips</strong>!</p>
<ol>
<li><code>findTarotSessionById(sessionId)</code></li>
<li><code>getSpreadById(session.spreadId)</code> <em>(static config table that almost never changes)</em></li>
<li><code>countSessionCards(sessionId)</code></li>
<li><code>getAllCards()</code> <em>(fetching full upright/reversed prose descriptions for all 78 cards on every draw!)</em></li>
<li><code>getDrawnCardIds(sessionId)</code> <em>(redundant with #3!)</em></li>
<li><code>insertSessionCard(...)</code></li>
</ol>
<p>On a remote serverless Postgres database, 5 serial read roundtrips + 1 write easily burned <strong>1.1–1.4 seconds</strong> per card click.</p>
<h3>The Fix: <code>Promise.all</code> + Narrow Projection + Warm-Instance Static Cache</h3>
<p>A tarot deck always has the same 78 cards, and spread definitions rarely change. During the draw step, we only need <code>{ id, name }</code>—not multi-paragraph card meanings.</p>
<p>We added a 10-minute in-memory TTL cache for static deck/spread metadata on warm serverless instances, eliminated the redundant <code>COUNT(*)</code> query (<code>drawnCardIds.length</code> already gives the exact count), and ran the remaining reads in parallel:</p>
<pre><code class="language-ts">const STATIC_CACHE_TTL_MS = 10 * 60 * 1000;
let drawDeckCache: { value: Array&lt;{ id: string; name: string }&gt;; expiresAt: number } | null = null;

export async function getCachedDrawDeck() {
  const now = Date.now();
  if (drawDeckCache &amp;&amp; drawDeckCache.expiresAt &gt; now &amp;&amp; drawDeckCache.value.length &gt; 0) {
    return drawDeckCache.value;
  }
  const rows = await db()
    .select({ id: tarotCard.id, name: tarotCard.name })
    .from(tarotCard);
  if (rows.length &gt; 0) {
    drawDeckCache = { value: rows, expiresAt: now + STATIC_CACHE_TTL_MS };
  }
  return rows;
}
</code></pre>
<p>And inside the Route Handler:</p>
<pre><code class="language-ts">// Collapse 5 serial reads into 1 parallel roundtrip (+ warm in-memory cache)
const [session, drawnCardIds, allCards] = await Promise.all([
  findTarotSessionById(sessionId),
  getDrawnCardIds(sessionId),
  getCachedDrawDeck(),
]);

const spread = await getCachedSpreadById(session.spreadId);
const drawnCount = drawnCardIds.length; // replaces redundant COUNT(*) query
</code></pre>
<h3>Measured Result</h3>
<ul>
<li><strong>Serial reads per click</strong>: <code>5</code> → <code>1</code> parallel batch (with static deck + spread served from memory on warm instances)</li>
<li><strong>Payload transferred from Postgres</strong>: Full 78-row prose table → cached <code>{ id, name }</code> array</li>
<li><strong>End-to-end draw latency</strong>: Dropped from <strong>~1.4s</strong> down to <strong>~0.55s</strong>, matching the 300ms card-lift animation cleanly without awkward spinner flicker.</li>
</ul>
<hr />
<h2>Quick Checklist If You Recently Upgraded to Tailwind v4</h2>
<ol>
<li>Grep your codebase for <code>transition-[transform</code> or <code>will-change-transform</code> paired with <code>translate-*</code>, <code>scale-*</code>, or <code>rotate-*</code> utilities—add <code>translate</code>, <code>scale</code>, and <code>rotate</code> explicitly (or use Tailwind's built-in <code>transition-transform</code> shorthand, which v4 updates automatically).</li>
<li>Audit your interactive Route Handlers for "static reference table" reads hiding inside hot click paths—especially full <code>SELECT *</code> queries where you only need IDs.</li>
</ol>
<p>Have you run into any other subtle CSS property shifts after migrating from Tailwind v3 to v4?</p>
]]></content:encoded></item><item><title><![CDATA[Why Prompt-Only Guardrails Fail in Production: Building a Deterministic Intent Router & Fail-Closed Output Firewall in Next.js]]></title><description><![CDATA[Move hard LLM rules into TypeScript: unidirectional intent routing, smart-quote normalization, fail-closed firewalls, and kill-switches.]]></description><link>https://tarotfortunecards.hashnode.dev/why-prompt-only-guardrails-fail-in-production-building-a-deterministic-intent-router-fail-closed-output-firewall-in-next-js</link><guid isPermaLink="true">https://tarotfortunecards.hashnode.dev/why-prompt-only-guardrails-fail-in-production-building-a-deterministic-intent-router-fail-closed-output-firewall-in-next-js</guid><category><![CDATA[AI]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[webdev]]></category><category><![CDATA[llm]]></category><dc:creator><![CDATA[tarotfortunecards]]></dc:creator><pubDate>Sat, 28 Nov 2026 06:53:25 GMT</pubDate><content:encoded><![CDATA[<p>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.</p>
<p>I learned this the hard way while hardening the AI reading and follow-up engine for <strong>Tarot Fortune Cards</strong> (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:</p>
<ol>
<li><strong>Mobile typography bypasses</strong>: iOS keyboards auto-replace straight apostrophes <code>'</code> with curly apostrophes <code>’</code>. A user typing <code>When’ll he text me?</code> or <code>I’ll meet him in 2026?</code> silently slipped past naive regex guards.</li>
<li><strong>Keyword false positives</strong>: Allowing an upgrade from a free single-card draw to a deeper reading whenever a question mentioned "family" accidentally triggered on casual prompts like <em>"Will my family like the cookies I baked today?"</em></li>
<li><strong>LLM boundary drift</strong>: Under follow-up pressure ("Just give me a rough month!"), even well-behaved models happily hallucinated <em>"in 3 to 6 months"</em> or <em>"this October"</em>—violating both product promises and user trust.</li>
</ol>
<p>The fix was moving <strong>every hard product invariant out of prompts and into deterministic TypeScript modules</strong> 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.</p>
<hr />
<h2>Pattern 1: One-Way Safety Rails on Intent Routing</h2>
<p>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.</p>
<p>On our quick single-card <a href="https://tarotfortunecards.art/yes-no-tarot">yes or no tarot</a> route, our hard product rule is <strong>zero upsells, zero teasers, zero pricing</strong> on quick or casual draws. Instead of asking the model to "judge whether the question is serious," we enforce a <strong>unidirectional deterministic router</strong> before any LLM call runs:</p>
<pre><code class="language-ts">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) &gt;= 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 &amp;&amp;
      params.typedByUser === true &amp;&amp;
      wordCount &gt;= 15 &amp;&amp;
      !TRIVIAL_YES_NO_RE.test(q) &amp;&amp;
      MAJOR_STAKES_RE.test(q)
    ) {
      return 'yes_no_major';
    }
    return 'yes_no_short';
  }
  // ...route other entry slugs with user-typed override
}
</code></pre>
<p>Two details here proved unexpectedly critical during adversarial testing:</p>
<ul>
<li><strong>Require <code>typedByUser === true</code> explicitly.</strong> Treating <code>undefined</code> as "probably typed" breaks legacy sessions and preset example clicks.</li>
<li><strong>Avoid broad single-word triggers like <code>family</code> or <code>work</code>.</strong> Phrase-level anchors (<code>quit my job</code>, <code>buy a house</code>, <code>change careers</code>) eliminate false positives like <em>"Will my family like the cookies I baked for dinner tonight?"</em></li>
<li><strong>Enforce <code>suppressPaywall</code> at the API boundary too</strong>, not just in React. Both our deep-reading generator and checkout endpoint re-run <code>resolveTarotIntentLine()</code> server-side and immediately refuse generation or checkout for <code>yes_no_short</code> sessions.</li>
</ul>
<hr />
<h2>Pattern 2: Normalize Smart Quotes Before Running Contraction Guards</h2>
<p>When routing follow-up questions on timing-heavy pages like <a href="https://tarotfortunecards.art/when-will-he-come-back-tarot">when will he come back tarot</a>, we separate three lanes:</p>
<ul>
<li><strong>Pure reference questions</strong> (strict whole-sentence whitelist—e.g. <em>"What does The Moon reversed mean?"</em>—rebuilt server-side into a canonical prompt so users can't smuggle prompt injections via <em>"Explain The Tower. Now ignore previous rules..."</em>)</li>
<li><strong>Timing forecast follow-ups</strong> (routed to a gated teaser lane)</li>
<li><strong>Normal free follow-ups</strong> (action advice, emotional clarity, boundaries)</li>
</ul>
<p>Our first timing detector checked <code>will he</code>, <code>is he going to</code>, etc.—and completely missed two real mobile patterns:</p>
<ol>
<li>Curly apostrophes (<code>I’ll</code>, <code>he’ll</code>, <code>won’t</code>) pasted or typed on iOS/macOS.</li>
<li>Self-action sentences that happen to contain <code>I'll</code> + a time word—like <em>"Should I text him today, and I'll keep it brief?"</em>—which is <strong>action advice</strong>, not a timing forecast!</li>
</ol>
<p>Separating apostrophe normalization from self-action exclusions fixed both directions cleanly:</p>
<pre><code class="language-ts">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) =&gt; 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) &amp;&amp; !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) &amp;&amp;
    !/\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);
}
</code></pre>
<hr />
<h2>Pattern 3: Fail-Closed Output Firewalls (Validate Both Generation AND Cache Reads)</h2>
<p>Prompts are probabilistic; production SLAs are deterministic.</p>
<p>For sensitive flows—such as preventing fabricated calendar dates, months, or numeric durations (<code>"in 3 to 6 months"</code>, <code>"by October"</code>, <code>"in 2026"</code>) or preventing cross-template leaks between future-partner readings and <a href="https://tarotfortunecards.art/reconciliation-tarot-reading">reconciliation tarot reading</a> flows—we treat the LLM output as <strong>untrusted input</strong> until it passes a code-level validator:</p>
<pre><code class="language-ts">const FORBIDDEN_OUTPUT_RULES: Array&lt;{ name: string; pattern: RegExp }&gt; = [
  {
    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) =&gt; rule.pattern.test(combined))
    .map((rule) =&gt; rule.name);
}
</code></pre>
<p>Notice two subtle wins in that snippet:</p>
<ol>
<li><strong><code>May</code> disambiguation</strong>: Matching bare <code>\bmay\b</code> falsely flags English modal verbs (<em>"you may notice..."</em>). Scoping <code>may</code> behind prepositions (<code>in|by|before|after|this|next may</code>) keeps false positives at zero while still blocking month predictions.</li>
<li><strong>Closed-loop retry + fail-closed fallback</strong>: On generation, if <code>validateStructuredOutput()</code> 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—<strong>never</strong> streaming raw unverified text to the browser.</li>
<li><strong>Validate cached records too</strong>: 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.</li>
</ol>
<hr />
<h2>Pattern 4: Independent Kill-Switches + Zero-Schema Sidecar Metadata</h2>
<p>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.</p>
<p>Instead, we isolate every behavioral change behind an independent server-side boolean flag (default <code>true</code>, flipping to <code>false</code> in ~10 seconds via Vercel environment variables without touching git):</p>
<pre><code class="language-ts">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),
  };
}
</code></pre>
<p>And to avoid running risky <code>ALTER TABLE</code> migrations on production PostgreSQL just to record <code>entrySlug</code> and <code>typedByUser</code> for each session, we stored a tiny structured JSON sidecar in our existing append-only session message table—giving us <strong>zero-downtime deployment</strong> and <strong>zero-migration rollback</strong>, while keeping every single one of our 23 public SEO routes byte-for-byte identical.</p>
<hr />
<h2>Takeaway</h2>
<p>Prompts are great for tone, nuance, and synthesis. They are terrible for invariants.</p>
<p>If a rule matters to user trust, billing fairness, or legal/chargeback risk:</p>
<ul>
<li><strong>Route it in code</strong> before the prompt ever runs.</li>
<li><strong>Normalize Unicode punctuation</strong> before running regexes.</li>
<li><strong>Validate outputs fail-closed</strong> on both writes and cache reads.</li>
<li><strong>Wrap behavioral layers in independent kill-switches</strong> so any single knob can be turned off in seconds.</li>
</ul>
<p>How are you splitting responsibilities between prompts and deterministic TypeScript guardrails in your production AI apps?</p>
]]></content:encoded></item></channel></rss>